skip to content

With OperationQueue, how do addDependency(_:), maxConcurrentOperationCount and cancelAllOperations() control tile download operations and the drawing step that depends on them?

level: middleimportance: should knowfreq 35%

answer

  1. what plain GCD queues lack
  2. not ready until dependencies finish
  3. the default lets the system decide
  4. cancel marks, it does not stop
  5. a cancelled dependency still counts as finished

basics

~20 s

addDependency(_:) keeps the draw operation from becoming ready until every download it depends on has finished, even across queues; maxConcurrentOperationCount caps how many downloads one queue runs at once; cancelAllOperations() only marks operations cancelled, so running ones must check isCancelled.

solid answer

~40 s

Wrap each tile download and the drawing step in `Operation` objects, often `BlockOperation`. `draw.addDependency(download)` means the draw operation is not ready until that download has finished, and dependencies work even when the operations sit on different queues, such as downloads on a private queue and drawing on `OperationQueue.main`. Setting `maxConcurrentOperationCount = 4` on the download queue caps how many of its operations run at once; the default, `OperationQueue.defaultMaxConcurrentOperationCount`, lets the system decide. `cancelAllOperations()` calls `cancel()` on every operation in that queue: queued ones are still started but finish without running their work, while running ones only see `isCancelled` become true and must stop themselves. The trap: a cancelled download counts as finished, so the dependent draw step becomes ready and runs unless you cancel it too or check its dependencies.

code

swift · 21 lines
swift
import Foundation

final class ConstellationJob {
    let downloads = OperationQueue()
    let draw = BlockOperation { print("drawing") }

    init(tileNames: [String]) {
        downloads.maxConcurrentOperationCount = 4
        for name in tileNames {
            let download = BlockOperation { print("downloading \(name)") }
            draw.addDependency(download)          // works across queues
            downloads.addOperation(download)
        }
        OperationQueue.main.addOperation(draw)
    }

    func userLeftScreen() {
        downloads.cancelAllOperations()  // queued downloads finish without running
        draw.cancel()                    // draw sits on another queue: cancel it too
    }
}

go deeper

for a junior

Recall that OperationQueue runs Operation objects such as BlockOperation, and that addDependency, maxConcurrentOperationCount and cancelAllOperations exist for ordering, throttling and cancelling.

for a middle

Explain readiness and cross-queue dependencies, what the default concurrency count means, and how cancellation treats queued versus executing operations.

for a senior

Catch the cancelled-dependency trap, where the draw step runs after its downloads were cancelled, and make long operations check isCancelled at sensible points.

for a principal

Judge when a dependency graph justifies OperationQueue over plain GCD or newer structured concurrency, and keep blocking waits out of UI code.

## What OperationQueue adds to GCD `OperationQueue`, in Foundation, runs `Operation` objects. Apple's documentation says operation queues use the Dispatch framework to start their operations, so this is a layer **on top of** GCD, not a rival to it. What it adds is a model of each unit of work as an object with state: - **Dependencies** between operations, even across queues. - A **concurrency cap** per queue. - **Cancellation** as a property every operation can check, plus `cancelAllOperations()`. - Key-value-observable state: `isReady`, `isExecuting`, `isFinished`, `isCancelled`. An `Operation` is single-shot: it runs once. Adding one that is already in a queue, executing or finished throws `NSInvalidArgumentException`. ## Dependencies `draw.addDependency(download)` makes `draw` not **ready** until `download` has finished. Several rules matter in practice: - Dependencies give an **absolute order**, even across queues. Apple's documentation stresses that queue order alone is not reliable, because readiness changes it. - An operation becomes ready when its **last** dependency finishes. - Dependencies make **no distinction between success and cancellation**. A cancelled operation is moved to the finished state, so anything depending on it becomes ready and runs. - Cycles are your bug: two operations that depend on each other never become ready. ## Limiting concurrency `maxConcurrentOperationCount` caps how many operations **this** queue runs at once; other queues run their own maximum in parallel. The default value, `OperationQueue.defaultMaxConcurrentOperationCount`, which the header recommends, lets the system pick a limit from current conditions. Lowering the value does not affect operations already executing. Setting it to 1 runs one operation at a time, but the queue still picks the highest-priority **ready** operation, so use dependencies, not the count, when order matters. ## Cancellation, step by step When the user leaves the constellation screen, the app calls `cancelAllOperations()` on the download queue: 1. The queue calls `cancel()` on every operation it holds; each one's `isCancelled` becomes true. 2. Operations still **waiting** stay in the queue. The queue must still call their `start()`, and the default `start()` sees the cancellation and finishes them without calling `main()`. Apple's documentation adds that cancelling an operation makes it ignore its own dependencies, so it can be flushed quickly. 3. Operations already **executing** keep running. Their code must check `isCancelled`, stop, and finish; nothing interrupts them. 4. Operations on **other queues**, such as the draw step on `OperationQueue.main`, are not touched. Because their cancelled dependencies now count as finished, they become ready and run. The rule is about the dependency, not the queue: if only the download is cancelled, a draw operation on the very same queue still executes. ## Fixing the trap - Cancel the dependent operation as well, as the snippet's `userLeftScreen()` does. - Or, inside the dependent operation, check whether any of its `dependencies` reports `isCancelled` and skip the work. - Or track success explicitly, since Apple's documentation leaves deciding what a failed dependency means to you. ## Writing an operation that honours cancellation A long download or decode is usually an `Operation` subclass rather than a `BlockOperation`, because the work needs to look at its own state while it runs: - Override `main()` for an operation that runs synchronously inside the queue's thread; the default `start()` calls it unless the operation was cancelled first. - Check `isCancelled` at the start of `main()` and again between expensive steps, such as after each chunk of a tile is decoded, and return early when it is true. - Leave the result untouched or mark it as cancelled, so a dependent step can tell a finished tile from an abandoned one. - Set `qualityOfService` on the operation, or on the queue, to match how urgently the user needs the result. A `BlockOperation` can carry several blocks through `addExecutionBlock(_:)`; Apple's documentation says it runs them concurrently and counts as finished only when all of them have finished. A queue you create invokes its operations on a separate thread, while `OperationQueue.main` runs one operation at a time on the main thread, interleaved with event handling and UI updates. ## OperationQueue or DispatchQueue? | Need | DispatchQueue | OperationQueue | |---|---|---| | Fire-and-forget background work | simplest choice | heavier | | Ordering between steps on different queues | manual, with callbacks or groups | `addDependency(_:)` | | Cap on parallel work | manual, for example with a semaphore | `maxConcurrentOperationCount` | | Cancelling queued work | `DispatchWorkItem.cancel()` per item | `cancel()` or `cancelAllOperations()` | | Waiting for a batch without blocking | `DispatchGroup.notify` | a dependent operation or `addBarrierBlock(_:)`, iOS 13 | Avoid the blocking calls in UI code: `waitUntilAllOperationsAreFinished()` and `addOperations(_:waitUntilFinished: true)` block the calling thread, and the SDK marks both unavailable from async code.

  • Without OperationQueue, how would you debounce the star search with GCD alone?
    Keep the pending `DispatchWorkItem`, call `cancel()` on it at each keystroke, then create a new one and schedule it with `asyncAfter(deadline: .now() + 0.3, execute:)`. `cancel()` stops an item that has not started; one already running keeps going and only sees `isCancelled` become true, so a slow search checks `isCancelled` before delivering results.
  • Does maxConcurrentOperationCount = 1 guarantee the order operations run in?
    It guarantees one at a time, not FIFO. The queue runs the highest-priority ready operation, and Apple's documentation warns against relying on queue order because changes in readiness alter it. When order matters, add dependencies, which the documentation says provide an absolute execution order.
  • How do you run code after a whole batch finishes without blocking a thread?
    Add one operation that depends on every operation in the batch, as the draw step does, or call `addBarrierBlock(_:)`, available since iOS 13, which runs after everything already enqueued has finished. `waitUntilAllOperationsAreFinished()` blocks the caller, and the SDK marks it unavailable from async code, pointing to `addBarrierBlock` or dependent operations instead.

  • Cancelling an operation stops its code immediately, wherever it is.
  • A cancelled dependency automatically cancels every operation that depends on it.
  • Dependencies only work between operations on the same OperationQueue.
  • maxConcurrentOperationCount = 1 makes operations run in the order they were added.
  • cancelAllOperations() removes every operation from the queue at once.