How to stop execution of a running background thread from main thread on swift while using DispatchQueue

前端 未结 2 1358
心在旅途
心在旅途 2021-02-04 17:21
 DispatchQueue.global(qos: .background).async {
    //This will run on the background queue
    self.writeValue(tag: GlobalData.WRITE_DATA, data: getDataForWrite(1) )
           


        
2条回答
  •  一向
    一向 (楼主)
    2021-02-04 17:28

    I think the best solution is to execute DispatchWorkItem in async:

    DispatchWorkItem encapsulates work that can be performed. A work item can be dispatched onto a DispatchQueue and within a DispatchGroup

    so at the end your code might be:

    let workItem = DispatchWorkItem {
       //.... writing stuff in background ....
    
       DispatchQueue.main.async {
          //.... done writing stuff, updating ui ....
       }
    }
    DispatchQueue.global().async(execute: workItem)
    

    when you need to stop the execution just call .cancel():

    //.... but, if stuff goes wrong ....
    DispatchQueue.main.async {
       workItem.cancel()
    }
    

提交回复
热议问题