ios - dispatch_group_t 或 dispatch_semaphore_t 等待多个异步请求完成
<p><p>我需要等待几个请求完成,然后才能继续下一个任务。 dispatch_group_t 和 dispatch_semaphore_t 在这里非常相似。所以我想知道哪个更好,或者这里没有太大区别。</p>
<pre><code>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
...
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>在这种特殊情况下,主要区别在于信号量方法使调用 <code>dispatch_semaphore_wait</code> 的线程保持事件状态,但一直阻塞,而 <code>dispatch_group_notify</code> 立即返回,仅稍后执行该 block ,使调用线程可以自由地做其他事情。我想说 <code>dispatch_group_notify</code> 在这种情况下是更好的选择。</p></p>
<p style="font-size: 20px;">关于ios - dispatch_group_t 或 dispatch_semaphore_t 等待多个异步请求完成,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/35604445/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/35604445/
</a>
</p>
页:
[1]