您如何等待主队列完成处理程序?
How do you wait on a main queue completion handler?
我想做的是按顺序执行一个 for 循环,在其中等待 completionHandler(),然后再开始下一次迭代。
- 在迭代
之前,我必须等待完成处理程序return
- 保证 return 完成处理程序
- 我正在尝试在较低优先级队列中同步等待
代码:
// we're on the main queue
for index in 0..<count {
var outcome: Any?
let semaphore = DispatchSemaphore(value: 0)
let queue = DispatchQueue(label: "\(index) iteration")
// this will access a UI component and wait for user to
// enter a value that's passed to the completion handler
funcWithCompletionHandler() { [weak self] (result) in
outcome = result
semaphore.signal()
}
// wait here for the completion handler to signal us
queue.sync {
semaphore.wait()
if let o = outcome {
handleOutcome(outcome)
}
}
// now, we iterate
}
我已经尝试了很多我在这里看到的其他解决方案,似乎没有任何效果。
我更喜欢使用背景组,您可以像这样在 class 上创建它的实例:
var group = DispatchGroup()
DispatchQueue.global(qos: .background).async {
self.group.wait()
// this part will execute after the last one left
// .. now, we iterate part
}
for index in 0..<count {
var outcome: Any?
let queue = DispatchQueue(label: "\(index) iteration")
funcWithCompletionHandler() { [weak self] (result) in
if let strongSelf = self {
outcome = result
strongSelf.group.enter() // group count = 1
}
}
queue.sync {
if let o = outcome {
handleOutcome(outcome)
self.group.leave()
// right here group count will be 0 and the line after wait will execute
}
}
}
我想做的是按顺序执行一个 for 循环,在其中等待 completionHandler(),然后再开始下一次迭代。
- 在迭代 之前,我必须等待完成处理程序return
- 保证 return 完成处理程序
- 我正在尝试在较低优先级队列中同步等待
代码:
// we're on the main queue
for index in 0..<count {
var outcome: Any?
let semaphore = DispatchSemaphore(value: 0)
let queue = DispatchQueue(label: "\(index) iteration")
// this will access a UI component and wait for user to
// enter a value that's passed to the completion handler
funcWithCompletionHandler() { [weak self] (result) in
outcome = result
semaphore.signal()
}
// wait here for the completion handler to signal us
queue.sync {
semaphore.wait()
if let o = outcome {
handleOutcome(outcome)
}
}
// now, we iterate
}
我已经尝试了很多我在这里看到的其他解决方案,似乎没有任何效果。
我更喜欢使用背景组,您可以像这样在 class 上创建它的实例:
var group = DispatchGroup()
DispatchQueue.global(qos: .background).async {
self.group.wait()
// this part will execute after the last one left
// .. now, we iterate part
}
for index in 0..<count {
var outcome: Any?
let queue = DispatchQueue(label: "\(index) iteration")
funcWithCompletionHandler() { [weak self] (result) in
if let strongSelf = self {
outcome = result
strongSelf.group.enter() // group count = 1
}
}
queue.sync {
if let o = outcome {
handleOutcome(outcome)
self.group.leave()
// right here group count will be 0 and the line after wait will execute
}
}
}