Sobes.tech
Junior — Middle

Is task cancellation possible when using GCD in iOS?

sobes.tech AI

Answer from AI

In GCD (Grand Central Dispatch) on iOS, canceling a task directly is not possible if the task has already started. GCD does not provide a built-in mechanism to interrupt a running block.

However, an indirect cancellation can be implemented:

  • Use flags or state variables that are checked within the task block, and if necessary, terminate execution early.
  • For asynchronous operations, use DispatchWorkItem, which supports the cancel() method. Canceling via DispatchWorkItem prevents the task from starting if it hasn't begun yet.

Example with DispatchWorkItem:

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

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

// Cancel the task
workItem.cancel()

Thus, cancellation is possible before the task starts or inside the task by checking the flag, but it is not possible to interrupt a block that is already executing.

Is task cancellation possible when using GCD in iOS… - sobes.tech