Eman Rezk
Eman Rezk

Reputation: 422

Correct way to cancel an AsyncTask in swift

I use DispatchQueue.main.async in UIViewController and i need to cancel async task when dismiss UIViewController

Upvotes: 3

Views: 3386

Answers (1)

Palle
Palle

Reputation: 12129

Grand Central Dispatch does not allow tasks to be cancelled from the outside when already running.

You basically have to check inside the asynchronously running task if your view controller still exists.

Assuming your call to GCD is directly in your UIViewController, so self refers to that view controller:

DispatchQueue.global().async { [weak self] in
    // Do work
    // Check if self still exists:
    guard let _ = self else {
        return // cancels the task
    }
    // Continue working
}

As self is only a weak reference to your view controller it will not stop the view controller from getting deallocated when dismissed. When it gets deallocated, self inside your GCD block becomes nil and you known that you can stop your task.

So you just have to check if self is nil every once in a while in your asynchronous block.


Note: Do not perform long running tasks on the main queue but in a global queue or even a private queue. Using the main queue blocks the main thread from performing other work like UI updates so your app freezes.

Upvotes: 6

Related Questions