Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a DispatchQueue that is running on the main thread

I have this block of code:

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

Now, I want to be able to stop this thread from executing. How can I stop it from being executed? For instance, after 3 seconds, I decide I don't want that to execute anymore so I want to stop it.

like image 875
Pablo Avatar asked Jun 19 '17 14:06

Pablo


People also ask

How do I cancel DispatchQueue?

You don't stop the queue. Instead, when the task that you dispatched starts executing, it needs to check its context and do the right thing (often: nothing) if the context has changed.

How do you stop a thread in Swift?

Cancel the thread Apart from terminating the thread, you can cancel it, by calling cancel() method on the thread's handle or inside the thread itself. This sets isCancelled property to true . For this feature to work, in the thread you need to check this flag periodically and then call exit if the flag is true .

Is DispatchQueue main concurrent?

A DispatchQueue is an abstraction layer on top of the GCD queue that allows you to perform tasks asynchronously and concurrently in your application.

Does task run on main thread Swift?

The first piece of your code runs on the main thread because the task initially runs on the main actor. But after the first await , your code can execute on any thread.


1 Answers

You can use DispatchWorkItems. They can be scheduled on DispatchQueues and cancelled before their execution.

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()
like image 61
Dávid Pásztor Avatar answered Sep 17 '22 21:09

Dávid Pásztor