iPhone - Grand Central Dispatch 主线程 [英] iPhone - Grand Central Dispatch main thread

查看:24
本文介绍了iPhone - Grand Central Dispatch 主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在我的应用程序中成功使用大型中央调度,但我想知道使用这样的东西的真正优势是什么:

I have been using with success, grand central dispatch in my apps, but I was wondering what is the real advantage of using something like this:

dispatch_async(dispatch_get_main_queue(), ^{ ... do stuff

甚至

dispatch_sync(dispatch_get_main_queue(), ^{ ... do stuff

我的意思是,在这两种情况下,您都在触发要在主线程上执行的块,这正是应用程序运行的位置,这无助于减少负载.在第一种情况下,您无法控制块何时运行.我见过在你触发块后半秒执行块的情况.第二种情况,类似于

I mean, in both cases you are firing a block to be executed on the main thread, exactly where the app runs and this will not help to reduce the load. In the first case you don't have any control when the block will run. I have seen cases of blocks being executed half a second after you fire them. The second case, it is similar to

[self doStuff];

对吗?

不知道大家怎么看.

推荐答案

分派一个块到主队列通常是从后台队列完成的,以表示某些后台处理已经完成,例如

Dispatching a block to the main queue is usually done from a background queue to signal that some background processing has finished e.g.

- (void)doCalculation
{
    //you can use any string instead "com.mycompany.myqueue"
    dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);

    dispatch_async(backgroundQueue, ^{
        int result = <some really long calculation that takes seconds to complete>;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateMyUIWithResult:result];
        });    
    });
}

在这种情况下,我们正在对后台队列进行冗长的计算,并且需要在计算完成后更新我们的 UI.更新 UI 通常必须从主队列完成,因此我们使用第二个嵌套的 dispatch_async 向主队列发信号".

In this case, we are doing a lengthy calculation on a background queue and need to update our UI when the calculation is complete. Updating UI normally has to be done from the main queue so we 'signal' back to the main queue using a second nested dispatch_async.

可能还有其他示例,您可能希望分派回主队列,但通常以这种方式完成,即嵌套在分派到后台队列的块中.

There are probably other examples where you might want to dispatch back to the main queue but it is generally done in this way i.e. nested from within a block dispatched to a background queue.

  • 后台处理完成 -> 更新 UI
  • 后台队列处理的数据块 -> 通知主队列开始下一个数据块
  • 后台队列中的传入网络数据 -> 通知主队列消息已到达
  • 等等等等

至于为什么您可能希望从主队列分派到主队列......好吧,您通常不会,尽管可以想象您可能会这样做来安排一些工作来完成接下来的工作运行循环的时间.

As to why you might want to dispatch to the main queue from the main queue... Well, you generally wouldn't although conceivably you might do it to schedule some work to do the next time around the run loop.

这篇关于iPhone - Grand Central Dispatch 主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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