gpt4 book ai didi

swift - DispatchGroup 中的几个任务。他们会按顺序运行吗?

转载 作者:行者123 更新时间:2023-11-28 10:03:17 25 4
gpt4 key购买 nike

在下面的代码中,附加到数组是否安全?是否保证维持秩序?

let processedData: [SomeType] = []
let dispatchGroup = DispatchGroup()
for _ in 0..<N {
dispatchGroup.enter()
startSomeAsyncTaskXYZ { (data, error) in
// handle error and process data
// add processed data to an array
processedData.append(..)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
// update UI
}

最佳答案

要坚持使用 DispatchGroup,同时保留所需的异步性质和预期的顺序,使您的数组成为一个可选数组,并按照任务完成的顺序填充它:

var processedData: [SomeType?] = Array(repeating: nil, count: N)
let dispatchGroup = DispatchGroup()
for idx in 0..<N {
dispatchGroup.enter()
startSomeAsyncTaskXYZ { (data, error) in
// Ensure we always .leave() after we're done
// handling the completion of the task
defer { dispatchGroup.leave() }

guard let data = data,
error == nil else {
// TODO: Actual error handling
return
}

// This needs to be .sync now (not .async) to ensure
// the deferred dispatchGroup.leave() is not called
// until *after* we've updated the array
DispatchQueue.main.sync {
processedData[idx] = SomeType(data: data)
}
}
}
dispatchGroup.notify(queue: .main) {
// update UI
}

关于swift - DispatchGroup 中的几个任务。他们会按顺序运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359393/

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