解雇View Controller不会停止异步任务 [英] Dismissing View Controller not stopping Async Task
本文介绍了解雇View Controller不会停止异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码从新启动的视图控制器中执行一些复杂的后台操作
I'm using the following code to do some complex background operations from a newly launched view controller
let globalQueue = DispatchQueue.global()
globalQueue.async {
//complex job
}
当用户单击取消"按钮时,我会致电
When the user clicks on the cancel button, I call
self.dismissViewController(self)
但这似乎并不能停止后台任务.
But it seems this does not stop the background task.
我该如何解决这个问题?
How can I solve this problem?
推荐答案
没有API可以取消正在运行的线程.相反,可以添加取消标志来签入处理响应.
There is no API that can cancel running thread. Instead, can add cancellation flag to check in handling response.
var dispatchItem:DispatchWorkItem!
func executeDispatch() {
dispatchItem = DispatchWorkItem {
for i in 1...200 {
sleep(1)
if !(self.dispatchItem.isCancelled) {
print("item \(i)")
}else {
print("cancel")
}
}
DispatchQueue.global().async(execute: dispatchItem)
}
func stop(_ sender: Any) {
DispatchQueue.global().async {
self.dispatchItem.cancel()
}
}
这篇关于解雇View Controller不会停止异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文