swift - 为什么我们从线程中移出闭包在 Grand Central Dispatch 中被调用?

标签 swift grand-central-dispatch

我正在学习 Swift 中的 Grand Central Dispatch。我了解到您可以创建自己的队列来执行代码。我还了解到您可以通过调用 main 返回到主线程。我一直在使用断点来观察线程,因为代码正在执行,试图更好地理解 GCD。我注意到以下内容并试图理解它。

  1. 我创建了自己的队列,名为 downloadQueue。我在这个队列上从 URLSession 调用 dataTask,并且在调用 dataTask() 的行上看到我在我创建的 downloadQueue 中。

enter image description here

  1. 在我进入 dataTask() 的完成处理程序的那一刻,我就不再在 downloadQueue 上了。我移动到队列:NSOperationQueue。

enter image description here

下面的代码是我的 dataTask()。

let downloadQueue = DispatchQueue(label: "downloadQueue", attributes: [])

downloadQueue.async { () -> 无效

    let dataTask = self.session!.dataTask(with: self.sessionURL!, completionHandler: { (data, response, error) -> Void in
    
    if error == nil
    {
        if data != nil
        {
            // Handle Data
        }
        else
        {
            // Handle Error
        }
    }
    else if error != nil
    {
        self.sendErrorCodeEmail(errorCodeMessage)  // The line from image2
    }
})

dataTask.resume()

我的理解是所有放在 downloadQueue.async{} 闭包中的代码都是在 downloadQueue 上执行的。为什么我会转到另一个队列?

  1. 如果我回调主线程,同样的事情也适用。一旦我进入 DispatchQueue.main.async{} 闭包,我就会回到 Queue: NSOperationQueue。这是为什么?

最佳答案

“为什么”的问题总是有点滑稽。在最直接的意义上,because that's just how URLSession works :

All delegate method calls and completion handlers related to the session are performed on this queue.

关于swift - 为什么我们从线程中移出闭包在 Grand Central Dispatch 中被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219904/

相关文章:

python - 使用 GCD 从 Cocoa 应用程序运行 Python 脚本

c++ - dispatch_async 会影响以下代码的性能吗?

swift - 串行队列内的并发队列调用?

ios - 在 UITableView 页脚 View 中定位自定义 UILabel

ios - Pod安装耗时长安装不上

javascript - WebView 变白/空白

ios - 带有 qos_class_user_interactive 的 global_queue

ios - 在不分派(dispatch)到主队列的情况下更新 UI 元素

swift - 如何快速从 Realm 数据库中获取唯一值

arrays - 无法快速将对象追加到对象数组中