gpt4 book ai didi

swift - 停止在主线程上运行的 DispatchQueue

转载 作者:搜寻专家 更新时间:2023-10-31 21:49:50 25 4
gpt4 key购买 nike

我有这段代码:

    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。它们可以在 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()

关于swift - 停止在主线程上运行的 DispatchQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44633729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com