GCD在主线程中执行任务 [英] GCD to perform task in main thread

查看:94
本文介绍了GCD在主线程中执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能来自任何线程的回调.当我收到此回调时,我想在主线程上执行某些任务.

I have a callback which might come from any thread. When I get this callback, then I would like to perform a certain task on the main thread.

我是否需要检查我是否已经在主线程上-否则在调用下面的代码之前不执行此检查是否有任何惩罚?

Do I need to check whether I already am on the main thread - or is there any penalty by not performing this check befora calling the code below?

dispatch_async(dispatch_get_main_queue(), ^{
   // do work here
});

推荐答案

否,您不需要检查是否已经在主线程上.通过将块分配到主队列,您只需调度要在主线程上串行执行的块,这将在运行相应的运行循环时发生.

No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.

如果您已经在主线程上,则行为是相同的:该块已调度,并在运行主线程的运行循环时执行.

If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.

这篇关于GCD在主线程中执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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