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")
}
}
我需要停止从主线程执行此线程。怎么可能
答案 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()
的更多信息
的更多信息