繁体   English   中英

为什么在第一个任务退出后调用 dispatchGroup.notify ?

[英]Why is dispatchGroup.notify called after only the first task has exited?

为什么在第一个任务退出后调用 dispatchGroup.notify ?

在以下代码中,输出如下:

1) Did the other thing 

**2) Did all the things** 

3) Did one thing 

4) done waiting

我希望:

1) Did the other thing 

2) Did one thing 

3) done waiting

**4) Did all the things** 

DispatchQueue.global().async {

        let dispatchGroup = DispatchGroup()

        dispatchGroup.notify(queue: DispatchQueue.main) {
            print("Did all the things")
        }


        dispatchGroup.enter()
        DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
        print("Did one thing")
            dispatchGroup.leave()

        }


        dispatchGroup.enter()
        DispatchQueue.global().async {
            print("Did the other thing")
            dispatchGroup.leave()
        }

        dispatchGroup.wait()
        print("done waiting")

    }

作为旁注,如果我在主线程上执行此操作,它会按预期工作。

根据非常小的 Apple 文档: https : //developer.apple.com/documentation/dispatch/dispatchgroup

func notify(queue: DispatchQueue, work: DispatchWorkItem) 当一组先前提交的块对象完成时,安排一个工作项提交到队列。

在上面的示例中,我在将块提交到队列之前调用了dispatchQueue.notify 通过如下更新代码,我能够获得预期的行为。

DispatchQueue.global().async {

        let dispatchGroup = DispatchGroup()



        dispatchGroup.enter()
        DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
        print("Did one thing")
            dispatchGroup.leave()

        }


        dispatchGroup.enter()
        DispatchQueue.global().async {
            print("Did the other thing")
            dispatchGroup.leave()
        }

        dispatchGroup.notify(queue: DispatchQueue.main) {
            print("Did all the things")
        }

        dispatchGroup.wait()
        print("done waiting")

    }

暂无
暂无

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

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