我知道这个主题已经有很多贡献。我尝试了不同的变体 DispatchGroup ,但似乎我无法让整个循环停止,直到某个任务完成。
let names = ["peter", "susan", "john", "peter", "susan", "john"]
var holding = [String: [Double]]()
for i in 0...10 {
for name in names {
if holding[name] == nil {
Alamofire.request("https://jsonplaceholder.typicode.com", parameters: parameters).responseJSON { responseData in
// do stuff here
holding[name] = result
}
} else {
// do other stuff with existing "holding[name]"
}
// if if holding[name] == nil, the whole process should wait
}
}
如果我使用 DispatchGroup,Alamofire 请求会一个接一个地执行,但整个循环无法识别 holding[name]
是否已经存在。所以 holding[name]
总是 nil
因为循环不等待。
非常感谢!
编辑:
根据 Mikes 和 Versus 的回答,我尝试了以下方法:
var names = ["peter", "susan", "john", "peter", "susan", "john"]
var holding = [String: [Double]]()
let semaphore = DispatchSemaphore(value: 1)
for i in 0...10 {
DispatchQueue.global().async { [unowned self] in
self.semaphore.wait()
for name in names {
if holding[name] != nil {
Alamofire.request("https://jsonplaceholder.typicode.com", parameters: parameters).responseJSON { responseData in
// do stuff here
holding[name] = result
semaphore.signal()
}
} else {
// do other stuff with existing "holding[name]"
semaphore.signal()
}
// if if holding[name] != nil, the wholeprocess should wait
}
}
}
但不幸的是,应用程序崩溃了。我做错了什么?
最佳答案
这里有两个选择
1 ) 信号量
2 ) 操作队列
但是在使用 Semaphores
之前你应该三思而后行
你需要小心 semaphore.signal()
和 semaphore.wait()
对
因为 Semaphore
可能会阻塞 Main Thread 所以所有操作都应该在 Dispatch.global.async
中完成
即
semaphore.wait()
Alamofire.request("https://jsonplaceholder.typicode.com", parameters: parameters).responseJSON { responseData in
semaphore.signal()
holding[name] = result
}
你在这里阻塞了主线程
问题在于完成处理程序在主线程中执行,该线程已被最初调用的 semaphore.wait() 锁定。所以当完成发生时, semaphore.signal() 永远不会被调用
你必须去
DispatchQueue.global().async { [unowned self] in
self.semaphore.wait()
// And other statemetns
}
希望对你和其他人有帮助
关于ios - 如何让循环等待任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091920/