小编典典

停止在主线程上运行的DispatchQueue

swift

我有这段代码:

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

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


阅读 495

收藏
2020-07-07

共1个答案

小编典典

您可以使用DispatchWorkItems。它们可以在DispatchQueues 上安排,并在执行前取消。

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()
2020-07-07