我可以不在循环中使用调度组吗? [英] Can I use dispatch group not in a loop?
问题描述
说在调用某些函数之前,我要完成3个不同的异步任务.我知道如果这些任务处于循环状态,可以使用调度组来执行此类操作,
Say I have 3 different asynchronous tasks I want to get done before calling some function. I'm aware of using dispatch groups to do such a thing if those tasks were in a loop,
var dispatchGroup = DispatchGroup()
for task in tasks {
dispatchGroup.enter()
DoSomeTask { (error, ref) -> Void in
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
DoSomeFunction()
})
但是,如果这些任务都具有相同的功能,但又不必彼此关联,例如将3个不同的值推送到数据库中,我会感到困惑.像这样:
However, I'm confused on how you'd do this if those tasks were all in the same function but didn't have to do with eachother, like pushing 3 different values to your database. Something like this:
updateDatabase() {
var dispatchGroup = DispatchGroup()
DoTask1 { (error, ref) -> Void in
}
DoTask2 { (error, ref) -> Void in
}
DoTask3 { (error, ref) -> Void in
}
}
在这种情况下,您将leave
和enter
语句放在哪里?
Where would you put the leave
and enter
statement in such a case as this?
推荐答案
在这种情况下,您的updateDatabase()
函数需要在完成所有更新后调用的完成块:
In this case your updateDatabase()
function needs a completion block that you call after all update are done:
updateDatabase(onSccess completion:() -> Void) {
var dispatchGroup = DispatchGroup()
dispatchGroup.enter()
DoTask1 { (error, ref) -> Void in
dispatchGroup.leave()
}
dispatchGroup.enter()
DoTask2 { (error, ref) -> Void in
dispatchGroup.leave()
}
dispatchGroup.enter()
DoTask3 { (error, ref) -> Void in
dispatchGroup.leave()
}
dispatchGroup.notify(queue: DispatchQueue.main) {
completion()
}
}
您不应该这样称呼它:
updateDatabase() {
//do somthing after updating
}
这篇关于我可以不在循环中使用调度组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!