Sobes.tech
Junior — Middle

Can the execution of a task launched via GCD in iOS or macOS be interrupted?

sobes.tech AI

Answer from AI

In GCD (Grand Central Dispatch), there is no built-in mechanism for interrupting or canceling a task that is already running. Once a task (block) is dispatched to a queue and begins executing, it cannot be stopped from outside.

To implement cancellation, flags or other synchronization mechanisms are usually used within the task itself, which are periodically checked, and if a cancellation request is detected, the task terminates properly.

An example approach with a flag:

var isCancelled = false

dispatchQueue.async {
    for i in 0..<1000 {
        if isCancelled {
            print("Task canceled")
            return
        }
        // perform work
    }
}

// To cancel
isCancelled = true

Thus, interruption is only possible if the task itself supports such logic.

Can the execution of a task launched via GCD in iOS… - sobes.tech