2017-06-19 168 views
0

上運行的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) 
    } 

現在,我希望能夠停止執行這個線程。我怎樣才能阻止它被執行?例如,3秒後,我決定不再執行,所以我想停止它。

+0

您可以使該塊無效https://stackoverflow.com/a/25120393/2000162 – TomCobo

回答

9

您可以使用DispatchWorkItem s。他們可以安排在DispatchQueue之前,並在執行前取消。

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

你可以使用一個一次性DispatchSourceTimer而非asyncAfter

var oneShot : DispatchSourceTimer! 

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

,並取消執行

oneShot?.cancel() 
oneShot = nil