Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 停止在主线程上运行的DispatchQueue_Swift_Grand Central Dispatch_Dispatch Queue - Fatal编程技术网

Swift 停止在主线程上运行的DispatchQueue

Swift 停止在主线程上运行的DispatchQueue,swift,grand-central-dispatch,dispatch-queue,Swift,Grand Central Dispatch,Dispatch Queue,我有一段代码: DispatchQueue.main.asyncAfter(deadline: .now() + (delay * Double(isDelayAccounted.hashValue)) + extraDelay) { self.isShootingOnHold = false self.shoot() self.shootingEngine = Timer.scheduledTimer(timeInterval: (Dou

我有一段代码:

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

现在,我希望能够阻止这个线程执行。我怎样才能阻止它被执行?例如,3秒钟后,我决定不再执行它,所以我想停止它。

您可以使用
DispatchWorkItem
s。它们可以在调度队列上调度,并在执行之前取消

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

您可以使用一次性的
DispatchSourceTimer
而不是
asyncAfter

var oneShot : DispatchSourceTimer!


并用

oneShot?.cancel()
oneShot = nil
可以使块无效
oneShot?.cancel()
oneShot = nil