我正在学习 Swift 中的 Grand Central Dispatch。我了解到您可以创建自己的队列来执行代码。我还了解到您可以通过调用 main 返回到主线程。我一直在使用断点来观察线程,因为代码正在执行,试图更好地理解 GCD。我注意到以下内容并试图理解它。
- 我创建了自己的队列,名为 downloadQueue。我在这个队列上从 URLSession 调用 dataTask,并且在调用 dataTask() 的行上看到我在我创建的 downloadQueue 中。
- 在我进入 dataTask() 的完成处理程序的那一刻,我就不再在 downloadQueue 上了。我移动到队列:NSOperationQueue。
下面的代码是我的 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 上执行的。为什么我会转到另一个队列?
- 如果我回调主线程,同样的事情也适用。一旦我进入 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/