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

查看:115
本文介绍了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

  • 后台队列处理的数据块 - >信号主队列以启动下一个块

  • 后台传入的网络数据queue - >消息已到达的信号主队列

  • 等等

  • background processing finished -> update UI
  • chunk of data processed on background queue -> signal main queue to start next chunk
  • incoming network data on background queue -> signal main queue that message has arrived
  • etc etc

至于为什么你可能想要从主队列中调度到主队列 ......好吧,你通常不会想到你可能会在下一次运行循环时安排一些工作。

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天全站免登陆