xcode 在主线程上调用 dispatch_sync(dispatch_get_global_queue()) 会导致应用程序“挂起”吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8783295/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:56:31  来源:igfitidea点击:

Does calling dispatch_sync(dispatch_get_global_queue()) on main thread cause app to "hang"?

objective-ciosxcodeobjective-c-blocksgrand-central-dispatch

提问by FlowUI. SimpleUITesting.com

// Method called when a button is clicked

- (void)handleClickEvent {
      dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         [self backgroundProcessing];
      });
      // Some code to update the UI of the view
      ....
      [self updateUI];
      ....
}

1) handleClickEvent is called on the main thread when a button on the view is pressed.

1)当按下视图上的按钮时,在主线程上调用handleClickEvent。

2) I used dispatch_sync() because the following code that updates the UI of the view cannot be done until a variable in the backgroundProcessing method is calculated.

2)我使用dispatch_sync()是因为在backgroundProcessing方法中的一个变量被计算之前,下面的更新视图UI的代码无法完成。

3) I used dispatch_get_global_queue in order to get the backgroundProcessing off the main thread. (following the rule: generally put background processing off main thread and generally put code that affect the UI on the main thread).

3)我使用 dispatch_get_global_queue 来从主线程中获取 backgroundProcessing。(遵循规则:一般将后台处理放在主线程之外,一般将影响UI的代码放在主线程上)。

My question is: Does the backgroundProcessing method "hang" the main thread until it is complete since I am using dispatch_sync?

我的问题是:自从我使用 dispatch_sync 以来,backgroundProcessing 方法是否“挂起”主线程直到它完成?

EDIT:Based on the answer below i have implemented this solution:

编辑:基于下面的答案,我已经实现了这个解决方案:

- (void)handleClickEvent {
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         [self backgroundProcessing];
         dispatch_async(dispatch_get_main_queue(), ^{
            [self updateUI];
         });
      });
}

solution from this link: Completion Callbaks

来自此链接的解决方案:Completion Callbaks

回答by Gary

Yes, dispatch_sync will block until the task is complete. Use dispatch_async and when the job is complete have it post a block back to the main queue to update the view.

是的,dispatch_sync 会阻塞直到任务完成。使用 dispatch_async 并在作业完成后将块发布回主队列以更新视图。