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

12,353

Solution 1

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()
}

Solution 2

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

Share:
12,353
krishnakumarcn
Author by

krishnakumarcn

Engineer. Flutter Evangelist

Updated on June 08, 2022

Comments

  • krishnakumarcn
    krishnakumarcn almost 2 years
     DispatchQueue.global(qos: .background).async {
        //This will run on the background queue
        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) )
        // .....
        DispatchQueue.main.async {
            //This will run on the main queue, after the previous code in outer block
            print("done writing data")
        }
    }
    

    I need to stop executing this thread from the main thread. How is it possible

  • Shyam
    Shyam about 6 years
    What if I want to run the above operation in background queue?
  • Kai
    Kai almost 2 years
    Please bear in mind that cancelling a work item will not cancel one that is already executing - developer.apple.com/documentation/dispatch/dispatchworkitem/‌​…