Dismissing View Controller not stopping Async Task

2019-02-21 03:02发布

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?

2条回答
【Aperson】
2楼-- · 2019-02-21 03:33

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()
        }
      }
查看更多
Animai°情兽
3楼-- · 2019-02-21 03:49

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)
查看更多
登录 后发表回答