派遣组通知似乎为时过早

时间:2018-09-22 01:29:31

标签: ios swift asynchronous grand-central-dispatch nsoperation

我正尝试按照此处https://stackoverflow.com/a/35906703/406322的建议使用调度组

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

DEBUG = True

输出是这样的:

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

1 个答案:

答案 0 :(得分: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.

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