gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:47:00 26 4
gpt4 key购买 nike

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

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

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所有请求。") 因为它在主优先级队列中?

尝试替换

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

通过:

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

在 Playground 上测试它工作正常:

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.

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

关于ios - 调度组通知似乎被调用得太早,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52452727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com