Sobes.tech
Junior — Middle

Is it possible to interrupt the execution of a task in GCD before it completes?

sobes.tech AI

Answer from AI

In GCD (Grand Central Dispatch), it is not possible to directly interrupt the execution of a task that has already started. Tasks sent to the queue are executed until completion.

However, you can implement task cancellation indirectly:

  • For asynchronous tasks, use DispatchWorkItem, which supports the cancel() method. The task itself should periodically check its isCancelled property and terminate correctly if cancellation is requested.

Example:

let workItem = DispatchWorkItem {
    for i in 0..<1000 {
        if workItem.isCancelled {
            print("Task cancelled")
            return
        }
        // Perform work
    }
}

DispatchQueue.global().async(execute: workItem)

// Later
workItem.cancel()

Thus, cancellation is only possible if the task supports checking for cancellation; otherwise, it cannot be forcibly interrupted.