For循环中的DispatchGroup [英] DispatchGroup in For Loop
问题描述
因此,我花了一些时间试图让DispatchGroup在长时间的异步操作完成之前阻止for循环迭代.我发现的大多数示例都相当简单明了,但是我似乎无法像我期望的那样使简单的测试用例正常工作.
So, I'm having a bit of a time trying to get DispatchGroup to keep a for loop from iterating before a long asynchronous operation has completed. Most examples I've found are fairly straight forward and clear, but I can't seem to get my simple test case to work as I would expect.
let group = DispatchGroup()
for i in 1...3 {
group.enter()
print("INDEX \(i)")
asynchronousOperation(index: i, completion: {
print("HELLO \(i)")
self.group.leave()
})
print("OUTSIDE \(i)")
}
func asynchronousOperation(index: Int, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+5) {
print("DONE \(index)")
completion()
}
}
这最终会打印
START
INDEX 1
OUTSIDE 1
INDEX 2
OUTSIDE 2
INDEX 3
OUTSIDE 3
DONE 1
HELLO 1
DONE 2
HELLO 2
DONE 3
HELLO 3
我希望它能打印出更多类似的东西
I would've expected it to print something more like
START
INDEX 1
OUTSIDE 1
HELLO 1
INDEX 2
OUTSIDE 2
HELLO 2
INDEX 3
OUTSIDE 3
HELLO 3
在OUTPIDE之后的下一个"INDEX"不会被打印,直到在异步操作()内部调用了group.leave()
Insofar as the next "INDEX" following an OUTSIDE wouldn't be printed until group.leave() had been called inside the asynchronousOperation()
可能是我误会了一些简单的东西-有什么想法吗?
Probably something simple I'm misunderstanding — any ideas?
推荐答案
执行以下代码以获得正确的输出:
execute the below code to get the proper output:
for i in 1...3 {
let semaphore = DispatchSemaphore(value: 0) // create a semaphore with a value 0. signal() will make the value 1.
print("INDEX \(i)")
asynchronousOperation(index: i, completion: {
print("HELLO \(i)")
semaphore.signal() // once you make the signal(), then only next loop will get executed.
})
print("OUTSIDE \(i)")
semaphore.wait() // asking the semaphore to wait, till it gets the signal.
}
func asynchronousOperation(index: Int, completion: @escaping () -> ()) {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+5) {
print("DONE \(index)")
completion()
}
}
输出:
索引1 外面1 完成1 HELLO 1
INDEX 1 OUTSIDE 1 DONE 1 HELLO 1
索引2 外2 完成2 HELLO 2
INDEX 2 OUTSIDE 2 DONE 2 HELLO 2
索引3 外3 完成3 HELLO 3
INDEX 3 OUTSIDE 3 DONE 3 HELLO 3
这篇关于For循环中的DispatchGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!