Swift Language Running Tasks in an OperationQueue


Example

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:

3.0
let mainQueue = OperationQueue.main

Create a custom OperationQueue:

3.0
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:

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

queue.addOperation(operation)

Add a block to an OperationQueue:

3.0
myQueue.addOperation {
    // some task
}

Add multiple Operations to an OperationQueue:

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

myQueue.addOperation(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:

3.0
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.