gpt4 book ai didi

ios - DispatchGroup 多次返回

转载 作者:行者123 更新时间:2023-11-30 13:03:40 24 4
gpt4 key购买 nike

下面的代码我用来进行并发 API调用。不知怎的,这个方法返回多次。我已经在没有 DispatchGroup 的情况下进行了测试,它按预期工作。帮我找出为什么它多次调用。

我的代码片段:

     func makeConcurrentCallForUpdating(_ parent: Parent,
completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void)
let fetchGroup = DispatchGroup()
let queue = DispatchQueue.global(qos: .default)
let endPoints = [.email, .others ]
DispatchQueue.concurrentPerform(iterations: endPoints.count) { (index) in
let enumType = endPoints[index]
switch enumType {
case .email:
updateEmail(parent, fetchGroup: fetchGroup, completionBlock: completionBlock)
case .others:
update(parent, fetchGroup: fetchGroup, completionBlock: completionBlock)
default:
break
}
}

fetchGroup.notify(queue: queue) {
if self.endPoints.count > 0 {
completionBlock(false, error)
} else {
self.saveUpdated(parent, completionBlock: completionBlock)
}
}
}

#MARK: EMAIL CALL
fileprivate func updateEmail(_ parent: Parent,
fetchGroup: DispatchGroup,
completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) {
fetchGroup.enter()
updateEmail(parent: parent) { (success, error) in
fetchGroup.leave()
}
}

最佳答案

在组中的任何任务leave()之前,您需要enter()所有已分派(dispatch)的任务。

fetchGroup.enter() 移到 DispatchQueue.concurrentPerform(...

之前
    let endPoints = [.email, .others ]
endPoints.forEach {_ in fetchGroup.enter()} //<- add this line
DispatchQueue.concurrentPerform(iterations: endPoints.count) { (index) in

并删除每个任务中的fetchGroup.enter():

fileprivate func updateEmail(_ parent: Parent,
fetchGroup: DispatchGroup,
completionBlock: @escaping (_ success: Bool, _ error: DescriptiveErrorType?) -> Void) {
//fetchGroup.enter() //<- remove this line, in your `update(...)` as well
updateEmail(parent: parent) { (success, error) in
fetchGroup.leave()
}
}

请尝试。

关于ios - DispatchGroup 多次返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39630420/

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