且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-09 18:14:01

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

I think the best solution is to execute DispatchWorkItem in async:

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

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)

当您需要停止执行时,只需调用 .cancel():

when you need to stop the execution just call .cancel():

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