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

时间:2018-09-06 12:51:55

标签: ios swift grand-central-dispatch

为什么只有第一个任务退出后才调用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")

    }

请注意,如果我在主线程上执行此操作,它将按预期工作。

1 个答案:

答案 0 :(得分:1)

根据极少的Apple文档:https://developer.apple.com/documentation/dispatch/dispatchgroup

  

func notify(队列:DispatchQueue,工作:DispatchWorkItem)   安排一组先前个已提交的块对象完成后,将工作项目计划提交到队列。

在上面的示例中,我将 notpatchQueue.notify 之前的代码称为 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")

    }