How can I be notified when a dispatch_async task is complete?

心不动则不痛 提交于 2019-12-18 15:08:33

问题


I have a asynchronous task like so:

dispatch_async(dispatch_get_main_queue(), ^{
     myAsyncMethodsHere;
});

Is there a way to be notified when the background task is complete?

Or to call a method upon completion?

I've read through the documentation and have looked into dispatch_after, but it seems to be more designed to dispatch the method after a certain length of time.

Thanks for the help.


回答1:


From the docs:

COMPLETION CALLBACKS

Completion callbacks can be accomplished via nested calls to the dispatch_async() function. It is important to remember to retain the destination queue before the first call to dispatch_async(), and to release that queue at the end of the completion callback to ensure the destination queue is not deallocated while the completion callback is pending. For example:

 void
 async_read(object_t obj,
         void *where, size_t bytes,
         dispatch_queue_t destination_queue,
         void (^reply_block)(ssize_t r, int err))
 {
         // There are better ways of doing async I/O.
         // This is just an example of nested blocks.

         dispatch_retain(destination_queue);

         dispatch_async(obj->queue, ^{
                 ssize_t r = read(obj->fd, where, bytes);
                 int err = errno;

                 dispatch_async(destination_queue, ^{
                         reply_block(r, err);
                 });
                 dispatch_release(destination_queue);
         });
 }

Source



来源:https://stackoverflow.com/questions/3379008/how-can-i-be-notified-when-a-dispatch-async-task-is-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!