调度组通知似乎被调用得太早

Dispatch group notify seems to get called too early

我正在尝试按照此处的建议使用调度组

但是,似乎 myGroup.notify 在 for 循环的所有迭代完成之前被调用。我做错了什么?

let myGroup = DispatchGroup()

for channel in channels.subscribedChannels() {
    myGroup.enter()

    buildUser(channel) { (success, user) in
        if success {
            addUser(user)
        }

        print("Finished request \(user.id)")
        myGroup.leave()
    }
}

myGroup.notify(queue: .main) {
    print("Finished all requests.")
}

输出是这样的:

Finished request 1
Finished all requests.
Finished request 2

不确定,但是你的 print("Finished request \(user.id)") 不是从线程调用的,因此可以在你的 print("Finished all requests.") 之后调用,因为它在主优先级队列上吗?

尝试替换

print("Finished request \(user.id)")

作者:

DispatchQueue.main.async {
    print("Finished request \(user.id)")
}

在操场上进行测试效果很好:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

class User {
    var id: Int
    init(id: Int) {
        self.id = id
    }
}

class Channel {
    var user: User
    init(user: User) {
        self.user = user
    }
}

var subscribedChannels: [Channel] = []
let user1 = User(id: 1)
let user2 = User(id: 2)
subscribedChannels.append(Channel(user: user1))
subscribedChannels.append(Channel(user: user2))
let myGroup = DispatchGroup()
let bgQueue = DispatchQueue.global(qos: .background)

func doSomething(channel: Channel, callback: @escaping (Bool, User) -> Void) {
    print("called for \(channel.user.id)")
    bgQueue.asyncAfter(deadline: .now() + 1) {
        callback(true, channel.user)
    }
}

for channel in subscribedChannels {
    myGroup.enter()
    doSomething(channel: channel) { (success, user) in
        if success {
            //
        }

        print("Finished request \(user.id)")
        myGroup.leave()
    }
}

myGroup.notify(queue: .main) {
    print("Finished all requests.")
}

这会打印

called for 1
called for 2

然后 1 秒后

Finished request 1
Finished request 2
Finished all requests.

我不知道你的类和方法,所以我很难知道更多