我的代码设置如下。据我了解,队列 1 应该完成所有操作,然后移至队列 2。但是,一旦我的异步操作开始,queue2 就会开始。这违背了 GCD 的目的……我做错了什么?这输出:
完成了吗
队列 2
然后一段时间后,打印图像下载成功
..我想说清楚,如果我在 queue1 中放入其他代码,例如 print("test") 或循环 0..10 打印 i,所有这些操作将在移动到 queue2 之前完成。似乎异步下载搞砸了,我该如何解决这个问题?任何地方都没有文档,我使用了来自 AppCoda 的非常有用的指南 http://www.appcoda.com/grand-central-dispatch/
let queue1 = DispatchQueue(label: "com.matt.myqueue1")
let queue2 = DispatchQueue(label: "com.matt.myqueue2")
let group1 = DispatchGroup()
let group2 = DispatchGroup()
let item = DispatchWorkItem{
// async stuff happening like downloading an image
// print success if image downloads
}
queue1.sync(execute: item)
item.notify(queue1, execute: {
print("did this finish?")
})
queue2.sync {
print("queue2")
}
最佳答案
let item = DispatchWorkItem{
// async stuff happening like downloading an image
// print success if image downloads
}
好的,定义它,但还没有运行。
queue1.sync(execute: item)
执行 item
并开始它的异步事件。之后立即返回。这里没有说“等待那些不相关的异步事件完成”。系统甚至没有办法知道您调用的函数内部还有其他异步调用。它如何知道 object.doit()
是否包含异步调用(以及这些调用是否是您打算等待的异步调用)?它只知道 item
何时返回,继续。
这就是 group1
的用途(您似乎没有将它用于任何用途)。在这些“异步发生的事情”中的某个地方,你应该通过离开组来告诉系统它已完成。 (我不知道 group2
是做什么用的。它也从未被使用过。)
item.notify(queue1, execute: {
print("did this finish?")
})
item
已经完成。我们知道它必须已经完成,因为它是使用sync
运行的,并且直到它的项目完成才会返回。所以这个 block 将立即安排在 queue1
上。
queue2.sync {
print("queue2")
}
完全不相关并且可以在“完成此操作”代码之前或之后运行,我们在 queue2
上安排了一个 block 。
你的意思可能是:
let queue1 = DispatchQueue(label: "com.matt.myqueue1")
let group1 = DispatchGroup()
group1.enter()
// Kick off async stuff.
// These usually return quickly, so there's no need for your own queue.
// At some point, when you want to say this is "done", often in some
// completion handler, you call group1.leave(), for example:
... completionHandler: { group1.leave() }
// When all that finishes, print
group.notify(queue: queue1) { print("did this finish?") }
关于swift - 通用大中央调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494904/