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

前端 未结 2 1356
心在旅途
心在旅途 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:40

    You can use a BlockOperation

    let blockOperation = BlockOperation {
        self.writeValue(tag: GlobalData.WRITE_DATA, data: getDataForWrite(1) )
        self.writeValue(tag: GlobalData.WRITE_DATA, data: getDataForWrite(2) )
        self.writeValue(tag: GlobalData.WRITE_DATA, data: getDataForWrite(3) )
        self.writeValue(tag: GlobalData.WRITE_DATA, data: getDataForWrite(4) )
        self.writeValue(tag: GlobalData.WRITE_DATA, data: getDataForWrite(5) )
        //...
    }
    
    let queue = OperationQueue()
    queue.addOperation(blockOperation)
    

    And at some point in time from your main thread you can cancel the operation:

    blockOperation.cancel()
    

    More info on BlockOperation

    More info on OperationQueue

提交回复
热议问题