iOS GCD与异步块同步 [英] iOS GCD Sync with Async Block

查看:117
本文介绍了iOS GCD与异步块同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带块的异步函数:

I have an async function with a block :

[self performAsyncTaskCompletion:(void(^) () )
 {
   //Do Something
 }
];

我需要多次调用此函数,但需要同步调用。我尝试使用GCD队列:

I need to call this function many times but in a synchronous way. I tried to use GCD queues :

dispatch_queue_t queue = dispatch_queue_create("com.MyApp.task", NULL);
for (int i = 0; i < array.count; i++)
{
   dispatch_sync(queue, ^{
     [self performAsyncTaskCompletion:(void(^) () )
      {
        //Do Something
      }
      ];
   });
}

但它不起作用因为dispatch_sync只等待结束块。
如何让它等待其块中异步函数的结束?

But it doesn't work because dispatch_sync is only waiting for the end of the block. How can I ask it to wait for the end of the async functions in its block ?

推荐答案

你可以使用如果要在完成一系列异步任务后启动某个进程,但是希望允许这些任务相互之间同时运行(特别是对于网络请求,可以提供比运行它们更好的性能),则调度组顺序):

You could use dispatch group if you want to initiate some process upon the completion of a series of asynchronous tasks, but would like to allow those tasks to run concurrently with respect to each other (which, especially with network requests, can offer much better performance than running them sequentially):

dispatch_group_t group = dispatch_group_create();

for (int i = 0; i < array.count; i++) {
    dispatch_group_enter(group);
    [self performAsyncTaskCompletion: ^{
        //Do Something
        dispatch_group_leave(group);
    }];
}

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    // do this when its all done
});

就个人而言,我甚至可能倾向于对 performAsyncTaskCompletion ,改为使用异步 NSOperation 子类模式。然后你可以将这些添加到 NSOperationQueue ,并指定 maxConcurrentOperationCount ,从而实现相同的并发性,同时还控制并发度。但希望上面说明了这个想法:同时运行任务,但检测这些任务的完成情况,而不会阻塞主线程。

Personally, I'd might even be inclined to perform a more radical refactoring of performAsyncTaskCompletion, using an asynchronous NSOperation subclass pattern instead. Then you could add these to a NSOperationQueue with maxConcurrentOperationCount specified, thereby achieving the same concurrency while also controlling the degree of concurrency. But hopefully the above illustrates the idea: Run tasks concurrently, but detect the completion of those tasks without ever blocking the main thread.

这篇关于iOS GCD与异步块同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆