ios - 什么是默认线程

标签 ios swift multithreading

iOS中,我们有GCDOperation来处理并发编程。

查看 GCD 我们有 QoS 类,它们简单明了,这个问题是关于为什么 DispatchQueue.main.async 通常用于 Main Thread 中的异步 X 任务。

因此,当我们通常在 UI 中处理某些更新时,我们通常会使用该功能来防止应用程序出现任何不响应。

让我觉得在 UIViewController 中编写代码通常在主线程中执行?

但也知道 callback & completionHandler 通常在不指定它们所在线程的情况下执行,并且 UI 从来没有遇到过问题!!所以它在背景上?

Swift 如何处理这个问题?默认情况下我在哪个线程上写而不指定任何内容?

最佳答案

既然这里的问题不止一个,我们就试着一一解答吧。

why DispatchQueue.main.async is commonly used to asynchronies X tasks in the Main Thread.

在提及直接答案之前,请确保您没有理解上的混淆:

  • 串行 <===> 并发。
  • 同步 <===> 异步。

请记住 DispatchQueue.main串行队列。使用 syncasync 与确定队列的序列化currency 无关,而是指如何任务已处理。因此说 DispatchQueue.main.async 意味着:

returns control to the current queue right after task has been sent to be performed on the different queue. It doesn't wait until the task is finished. It doesn't block the queue.

cited from: https://stackoverflow.com/a/44324968/5501940 (I'd recommend to check it.)

换句话说,async 意味着:这将在主 thead 上发生并在它完成时更新它。这就是你所说的:

So when we usually handle updating something in the UI we usually use that function since to prevent any irresponsiveness from the application.

似乎是明智的;使用 sync - 而不是 async - 将阻塞 main.


makes me think is writing code inside the UIViewController usually executed in the main thread ?

首先:默认情况下,没有指定哪个线程应该执行一段代码,它将是主线程。但是,您的问题似乎并不具体,因为在 UIViewController 中,我们可以通过指定它来调用未在主线程上执行的功能。


but also knowing that callback & completionHandler usually execute without specifying on what thread they are in, and the UI never had a problem with that !! so it is on the background ?

“知道回调和 completionHandler 通常在不指定它们所在线程的情况下执行”不!你必须指定它。一个很好的真实例子,实际上就是这样 Main Thread Checker有效。

我相信你在这里遗漏了一些东西,当处理 UIKit 中的内置方法时 - 例如 - 返回一个完成处理程序,我们看不到它包含调用完成处理程序时类似于 DispatchQueue.main.async;因此,如果您没有在 DispatchQueue.main.async 中的完成处理程序中执行代码,那么我们应该假设它会为您处理!这并不意味着它没有在某处实现。

另一个真实世界的例子,A​​lamofire!调用时

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    // what is going on here work has to be async on the main thread
}

这就是为什么您可以调用它而不会在主线程上遇到任何“挂起”问题的原因;这并不意味着它没有处理,而是意味着他们会为您处理,因此您不必担心。

关于ios - 什么是默认线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55019750/

相关文章:

ios - Receipt Refresh导致Apple Review因iTunes Store连接错误拒绝App

ios - 不支持游戏中心成就

arrays - Swift - NSDictionary 多维

java - 安卓和Java : use of runnable

ios - 2个UIScrollViews的直通触摸

ios - UITableView 部分标题不可见

ios - 如何从 swift 2.1 中的对象数组创建字典?

ios - Swift:拖放,保存来自谷歌图像的图像网址

C# async 周期性调用方法

java - 定时器任务和线程以及内部类