如何在使用DispatchQueue

时间:2018-01-16 12:04:18

标签: ios swift multithreading grand-central-dispatch

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

我需要停止从主线程执行此线程。怎么可能

2 个答案:

答案 0 :(得分:11)

我认为最好的解决方案是在DispatchWorkItem中执行async

  

DispatchWorkItem封装了可以执行的工作。可以将工作项分派到DispatchQueue和DispatchGroup

所以最后你的代码可能是:

let workItem = DispatchWorkItem {
   //.... writing stuff in background ....

   DispatchQueue.main.async {
      //.... done writing stuff, updating ui ....
   }
}
DispatchQueue.global().async(execute: workItem)

当您需要停止执行时,只需致电.cancel()

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

答案 1 :(得分:1)

您可以使用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)

在主线程的某个时间点,您可以取消操作:

blockOperation.cancel()

有关BlockOperation

的更多信息

有关OperationQueue

的更多信息