如何在使用DispatchQueue时停止从主线程快速执行正在运行的后台线程 [英] How to stop execution of a running background thread from main thread on swift while using DispatchQueue

查看:63
本文介绍了如何在使用DispatchQueue时停止从主线程快速执行正在运行的后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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

推荐答案

我认为最好的解决方案是在 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()
}

这篇关于如何在使用DispatchQueue时停止从主线程快速执行正在运行的后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆