Почему dispatchGroup.notify вызывается только после завершения первой задачи? - PullRequest
0 голосов
/ 06 сентября 2018

Почему 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 голосов
/ 06 сентября 2018

В соответствии с очень минимальным количеством документов 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")

    }
...