如何让我的代码等待,直到DispatchQueue中的任务完成?是否需要任何CompletionHandler或其他东西?
func myFunction() { var a: Int? DispatchQueue.main.async { var b: Int = 3 a = b } // wait until the task finishes, then print print(a) // - this will contain nil, of course, because it // will execute before the code above }
我正在使用Xcode 8.2并在Swift 3中编写。
使用DispatchGroups可以实现这一点。您可以在群组enter()和leave()通话达到平衡时得到通知:
DispatchGroup
enter()
leave()
func myFunction() { var a: Int? let group = DispatchGroup() group.enter() DispatchQueue.main.async { a = 1 group.leave() } // does not wait. But the code in notify() gets run // after enter() and leave() calls are balanced group.notify(queue: .main) { print(a) } }
或者您可以等待:
func myFunction() { var a: Int? let group = DispatchGroup() group.enter() // avoid deadlocks by not using .main queue here DispatchQueue.global(attributes: .qosDefault).async { a = 1 group.leave() } // wait ... group.wait() print(a) // you could also `return a` here }
注意 :group.wait()阻止当前队列(在您的情况下可能是主队列),因此您必须dispatch.async在另一个队列上(如上面的示例代码中)以避免 死锁 。
group.wait()
dispatch.async