gpt4 book ai didi

ios - 如何在使用 DispatchQueue 时停止从主线程快速执行正在运行的后台线程

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:51 24 4
gpt4 key购买 nike

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

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

最佳答案

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

DispatchWorkItem encapsulates work that can be performed. A work item can be dispatched onto a DispatchQueue and within a 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()
}

关于ios - 如何在使用 DispatchQueue 时停止从主线程快速执行正在运行的后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48280851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com