Sobes.tech
Junior — Middle

Is it possible to interrupt a task running via GCD during its execution?

sobes.tech AI

Answer from AI

In GCD (Grand Central Dispatch), there is no built-in mechanism to forcibly stop a task that has already started. Once a task (block) has begun executing, it cannot be interrupted from outside.

To implement the ability to cancel, you need to manually check a cancellation flag within the task itself. For example, use an atomic variable or a flag that is periodically checked during execution, and if necessary, terminate early.

Example:

var isCancelled = false

dispatchQueue.async {
    for i in 0..<1000 {
        if isCancelled {
            print("Task cancelled")
            break
        }
        // Perform part of the work
    }
}

// Somewhere else
isCancelled = true

For more flexible cancellation, consider using Operation and OperationQueue, which have built-in support for cancelling operations.

Is it possible to interrupt a task running via GCD… - sobes.tech