objective-c 主线程中的 dispatch_get_main_queue()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18847438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dispatch_get_main_queue() in main thread
提问by B.S.
I have method which makes UI changes in some cases.
我有在某些情况下更改 UI 的方法。
For example:
例如:
-(void) myMethod {
if(someExpressionIsTrue) {
// make some UI changes
// ...
// show actionSheet for example
}
}
Sometimes myMethodis called from the mainThreadsometimes from some other thread.
有时myMethod是从mainThread有时从一些中调用的other thread。
Thats is why I want these UI changes to be performed surely in the mainThread.
这就是为什么我希望在mainThread.
I changed needed part of myMethodthis way:
我以myMethod这种方式改变了需要的部分:
if(someExpressionIsTrue) {
dispatch_async(dispatch_get_main_queue(), ^{
// make some UI changes
// ...
// show actionSheet for example
});
}
So the questions:
所以问题:
- Is it safe and good solution to call
dispatch_async(dispatch_get_main_queue()in main thread? Does it influence on performance? - Can this problem be solved in the other better way?I know that I can check if it is a main thread using
[NSThread isMainThread]method and calldispatch_asynconly in case of other thread, but it will make me create one more method or block with these UI updates.
dispatch_async(dispatch_get_main_queue()在主线程中调用是否安全且良好的解决方案?它对性能有影响吗?- 这个问题可以用其他更好的方式解决吗?我知道我可以使用
[NSThread isMainThread]方法检查它是否是主线程并dispatch_async仅在其他线程的情况下调用,但这会让我创建更多方法或使用这些 UI 更新块。
回答by Abizern
There isn't a problem with adding an asynchronous block on the main queue from within the main queue, all it does is run the method later on in the run loop.
从主队列中在主队列上添加异步块没有问题,它所做的只是稍后在运行循环中运行该方法。
What you definitely don't want to do is to call dispatch_syncadding a block to the main queue from within the main queue as you'll end up locking yourself.
您绝对不想做的是dispatch_sync从主队列中调用向主队列添加一个块,因为您最终会锁定自己。
回答by Zhengming Ying
Don't worry if you are calling dispatch_async in main thread or not. iOS will put the block in a queue and execute the block in main thread.
如果您在主线程中调用 dispatch_async ,请不要担心。iOS 会将该块放入队列并在主线程中执行该块。

