停止在主线程上运行的DispatchQueue

Pab*_*blo 4 grand-central-dispatch swift dispatch-queue

我有这段代码:

    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)   
    }
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够阻止此线程执行.怎么能阻止它被执行?例如,3秒后,我决定我不想再执行,所以我想停止它.

Dáv*_*tor 21

你可以使用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()
Run Code Online (Sandbox Code Playgroud)


vad*_*ian 7

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

var oneShot : DispatchSourceTimer!
Run Code Online (Sandbox Code Playgroud)
 oneShot = DispatchSource.makeTimerSource(queue: DispatchQueue.main)
 oneShot.scheduleOneshot(deadline: .now() + (delay * Double(isDelayAccounted.hashValue)) + extraDelay))
 oneShot.setEventHandler {
     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)   
 }
 oneShot.setCancelHandler {
     // do something after cancellation
 }

 oneShot.resume()
Run Code Online (Sandbox Code Playgroud)

并取消执行

oneShot?.cancel()
oneShot = nil
Run Code Online (Sandbox Code Playgroud)