Dismissing View Controller not stopping Async Task

前端 未结 2 928
你的背包
你的背包 2021-01-07 13:07

I\'m using the following code to do some complex background operations from a newly launched view controller

 let globalQueue = DispatchQueue.global()
  glob         


        
相关标签:
2条回答
  • 2021-01-07 13:13

    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)
    
    0 讨论(0)
  • 2021-01-07 13:19

    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()
            }
          }
    
    0 讨论(0)
提交回复
热议问题