简体   繁体   English

Swift DispatchGroup 在任务完成前通知

[英]Swift DispatchGroup notify before task finish

I'm using DispatchGroup to perform a task, but group.notify is being called before the task is completed.我正在使用DispatchGroup执行任务,但在任务完成之前调用了group.notify

My code:我的代码:

let group = DispatchGroup()
let queueImage = DispatchQueue(label: "com.image")
let queueVideo = DispatchQueue(label: "com.video")
queueImage.async(group: group) {
    sleep(2)
    print("image")
}

queueVideo.async(group: group) {
    sleep(3)
    print("video")
}

group.notify(queue: .main) {
    print("all finished.")
}

Logs:日志:

all finish.
image
video

Update: The question above actually runs correctly as is (as rmaddy pointed out!)更新:上面的问题实际上按原样正确运行(正如 rmaddy 指出的!)

I'm saving this wrong answer below in case others get confused about DispatchQueue's async(group:) methods behavior, since Apple's swift doc on it is currently lousy.我在下面保存这个错误的答案,以防其他人对 DispatchQueue 的 async(group:) 方法行为感到困惑,因为Apple 的 swift 文档目前很糟糕。


The group's enter() needs to be called before each call to async(), and then the group's leave() needs to be called at end of each async() block, but within the block.组的 enter() 需要在每次调用 async() 之前调用,然后组的 leave() 需要在每个 async() 块的末尾调用,但块内。 It's basically like a refcount that when it reaches zero (no enters remaining), then the notify block is called.它基本上就像一个引用计数,当它达到零(没有剩余的输入)时,就会调用通知块。

let group = DispatchGroup()
let queueImage = DispatchQueue(label: "com.image")
let queueVideo = DispatchQueue(label: "com.video")

group.enter()
queueImage.async(group: group) {
    sleep(2)
    print("image")
    group.leave()
}

group.enter()
queueVideo.async(group: group) {
    sleep(3)
    print("video")
    group.leave()
}

group.notify(queue: .main) {
    print("all finished.")
}

Generic answer : (Swift 5)通用答案:(Swift 5)

let yourDispatchGroup = DispatchGroup()

yourDispatchGroup.enter()
task1FunctionCall {
  yourDispatchGroup.leave() //task 1 complete
}

yourDispatchGroup.enter()
task2FunctionCall {
  yourDispatchGroup.leave() //task 2 complete
}

.. ..
yourDispatchGroup.enter()
tasknFunctionCall {
  yourDispatchGroup.leave() //task n complete
}

dispatchGroup.notify(queue: .main) {
  //This is invoked when all the tasks in the group is completed.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM