在主要功能runTask()
中调用的功能列表中,我有一系列使用Alamofire顺序发出的HTTP请求,我希望它们能够停止。因此,我为需要运行的每个任务在runTask()
中设置了DispatchWorkItem
函数调用,并将工作项存储在数组中,如下所示:
taskWorkItems.append(DispatchWorkItem { [weak self] in
concurrentQueue!.async {
runTask(task: task)
}
})
然后,我迭代工作项数组,并像这样调用perform()
函数:
for workItem in taskWorkItems {
workItem.perform()
}
最后,我的应用程序中有一个按钮,当点击该按钮时,我想取消工作项,并且我使用以下代码来实现这一目的:
for workItem in taskWorkItems {
concurrentQueue!.async {
workItem.cancel()
print(workItem.isCancelled)
}
}
workItem.isCancelled
打印到true
;但是,我在runTask()
调用的函数中设置了日志,即使调用了workItem.cancel()
并且workItem.isCancelled
打印true
,我仍然看到函数正在执行。我在做错什么,如何停止执行功能?
答案 0 :(得分:2)
TLDR:如果要运行的任务尚未执行,则调用cancel可以阻止其执行,但是不会暂停已经执行的任务。
因为与此相关的苹果文档是裸露的...
https://medium.com/@yostane/swift-sweet-bits-the-dispatch-framework-ios-10-e34451d59a86
A dispatch work item has a cancel flag. If it is cancelled before running, the dispatch queue won’t execute it and will skip it. If it is cancelled during its execution, the cancel property return True. In that case, we can abort the execution
//create the dispatch work item
var dwi2:DispatchWorkItem?
dwi2 = DispatchWorkItem {
for i in 1...5 {
print("\(dwi2?.isCancelled)")
if (dwi2?.isCancelled)!{
break
}
sleep(1)
print("DispatchWorkItem 2: \(i)")
}
}
//submit the work item to the default global queue
DispatchQueue.global().async(execute: dwi2!)
//cancelling the task after 3 seconds
DispatchQueue.global().async{
sleep(3)
dwi2?.cancel()
}