在iOS中完成调度组操作后执行方法的延迟

时间:2013-04-08 14:09:51

标签: ios asynchronous queue grand-central-dispatch

我在调度组中的队列完成执行后调用了一个方法。但是,即使在执行了所有队列之后,执行最终方法也会有很大的延迟。任何人都可以解释任何可能的原因吗?

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_async(group, queue,^{
     //some code             
}


dispatch_group_notify(group, queue,
    ^{
        [self allTasksDone];
    });

我的意思是即使异步队列中的操作完成,也会在延迟一段时间后执行allTask​​sDone方法。

2 个答案:

答案 0 :(得分:2)

-allTasksDone如何运作?如果它通过更新用户界面元素与用户进行通信,则需要在主线程的上下文中运行,否则看起来有问题的UI元素被“延迟” - 直到主运行才会更新循环恰好使它们更新。

请改为尝试:

dispatch_group_notify(group, dispatch_get_main_queue(),
^{
    [self allTasksDone];
});

实际上,你在默认的后台队列上运行-allTasksDone,这对AppKit或UIKit不起作用。

答案 1 :(得分:0)

我建议采用另一种方法,尽管您可以使用调度组来完成此任务。

// Important note: This does not work with global queues, but you can use target queues to direct your custom queue to one of your global queues if you need priorities.
dispatch_queue_t queue = dispatch_queue_create("com.mycompany.myqueue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue,^{
     //some code             
}

dispatch_barrier_async(queue,
    ^{
        // this executes when all previously dispatched blocks have finished.
        [self allTasksDone];
    });