Swift Language Concurrency Running Tasks in an OperationQueue


You can think of an OperationQueue as a line of tasks waiting to be executed. Unlike dispatch queues in GCD, operation queues are not FIFO (first-in-first-out). Instead, they execute tasks as soon as they are ready to be executed, as long as there are enough system resources to allow for it.

Get the main OperationQueue:

let mainQueue = OperationQueue.main

Create a custom OperationQueue:

let queue = OperationQueue()
queue.name = "My Queue"
queue.qualityOfService = .default

Quality of Service specifies the importance of the work, or how much the user is likely to be counting on immediate results from the task.

Add an Operation to an OperationQueue:

// An instance of some Operation subclass
let operation = BlockOperation {
    // perform task here


Add a block to an OperationQueue:

myQueue.addOperation {
    // some task

Add multiple Operations to an OperationQueue:

let operations = [Operation]()
// Fill array with Operations


Adjust how many Operations may be run concurrently within the queue:

myQueue.maxConcurrentOperationCount = 3 // 3 operations may execute at once

// Sets number of concurrent operations based on current system conditions
myQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount

Suspending a queue will prevent it from starting the execution of any existing, unstarted operations or of any new operations added to the queue. The way to resume this queue is to set the isSuspended back to false:

myQueue.isSuspended = true

// Re-enable execution
myQueue.isSuspended = false

Suspending an OperationQueue does not stop or cancel operations that are already executing. One should only attempt suspending a queue that you created, not global queues or the main queue.