Swift DispatchGroup在任务完成前通知 [英] Swift DispatchGroup notify before task finish

查看:60
本文介绍了Swift DispatchGroup在任务完成前通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 DispatchGroup 执行任务,但是在任务完成之前将调用 group.notify .

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

我的代码:

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

日志:

all finish.
image
video

推荐答案

更新:上面的问题实际上按原样正确运行(如rmaddy所指出!)

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

如果其他人对DispatchQueue的async(group :)方法行为感到困惑,我会在下面保存这个错误答案,因为

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.

需要在每次调用async()之前调用组的enter(),然后需要在每个async()块的末尾调用组的Leave(),但是 within 堵塞.基本上就像refcount一样,当计数达到零(没有剩余输入)时,将调用notify块.

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

这篇关于Swift DispatchGroup在任务完成前通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆