我需要等待几个请求完成,然后才能继续执行下一个任务。 dispatch_group_t和dispatch_semaphore_t在这里非常相似。所以我想知道哪种更好,或者这里没有太大区别。

dispatch_group_t serviceGroup = dispatch_group_create();
dispatch_group_enter(serviceGroup);
// in completion block
dispatch_group_leave(serviceGroup);

//wait for all requests to complete
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
    // Won't get here until everything has finished
});

/* Or I can use dispatch_semaphore_t */

dispatch_semaphore_t sem = dispatch_semaphore_create(0);
// in completion block
dispatch_semaphore_signal(sem);
// before start request
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
// Reaching here means all requests has completed
...

最佳答案

在这种特殊情况下,关键区别在于信号量方法使调用dispatch_semaphore_wait的线程保持 Activity 状态,但在整个时间内一直处于阻塞状态,而dispatch_group_notify立即返回,仅稍后执行该块,使调用线程可以自由地执行其他操作。我想说,在这种情况下,dispatch_group_notify是更好的方法。

07-25 22:34