停止在主线程上运行的DispatchQueue [英] Stop a DispatchQueue that is running on the main thread

查看:213
本文介绍了停止在主线程上运行的DispatchQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

    DispatchQueue.main.asyncAfter(deadline: .now() + (delay * Double(isDelayAccounted.hashValue)) + extraDelay) {
        self.isShootingOnHold = false
        self.shoot()
        self.shootingEngine = Timer.scheduledTimer(timeInterval: (Double(60)/Double(self.ratePerMinute)), target: self, selector: #selector(ShootingEnemy.shoot), userInfo: nil, repeats: true)   
    }

现在,我希望能够停止执行该线程.如何阻止它执行?例如,三秒钟后,我决定不再执行该操作,因此我想停止它.

Now, I want to be able to stop this thread from executing. How can I stop it from being executed? For instance, after 3 seconds, I decide I don't want that to execute anymore so I want to stop it.

推荐答案

您可以使用DispatchWorkItem s.可以在DispatchQueue上安排它们,并在执行前将其取消.

You can use DispatchWorkItems. They can be scheduled on DispatchQueues and cancelled before their execution.

let work = DispatchWorkItem(block: {
    self.isShootingOnHold = false
    self.shoot()
    self.shootingEngine = Timer.scheduledTimer(timeInterval: (Double(60)/Double(self.ratePerMinute)), target: self, selector: #selector(ShootingEnemy.shoot), userInfo: nil, repeats: true)
})
DispatchQueue.main.asyncAfter(deadline: .now() + (delay * Double(isDelayAccounted.hashValue)) + extraDelay, execute: work)
work.cancel()

这篇关于停止在主线程上运行的DispatchQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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