Swift DispatchGroup notify before task finish

让人想犯罪 __ 提交于 2021-02-07 07:41:24

问题


I'm using DispatchGroup to perform a task, but group.notify is being called before the task is completed.

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

回答1:


Update: The question above actually runs correctly as is (as rmaddy pointed out!)

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.


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. 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.")
}



回答2:


Generic answer : (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.
}


来源:https://stackoverflow.com/questions/49376157/swift-dispatchgroup-notify-before-task-finish

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!