I\'m using the following code to do some complex background operations from a newly launched view controller
let globalQueue = DispatchQueue.global()
glob
Create the dispatch work item.
//create the dispatch work item
var disptachWorkItem:DispatchWorkItem?
Now put the complex task in dispatch work item.
dispatchWorkItem = DispatchWorkItem {
//Some complex job
}
Execute the Work on default global queue.
DispatchQueue.global().async(execute: dispatchWorkItem!)
You can find out when the viewController is being dismissed.
DispatchQueue.global.async {
dispatchWorkItem?.cancel()
}
presentingViewController?.dismissViewController(animated: true, completion: nil)
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()
}
}