Operation queue is a traditional Apple technology for asynchronously managing queue of pending tasks, with control over priorities, dependencies, degree of concurrency, cancelation, and allowing one to manage queue of tasks that are, themselves, asynchronous.
An operation queue is the Cocoa equivalent of a concurrent dispatch queue and is implemented by the OperationQueue
class. It is built upon the grand-central-dispatch (GCD) framework. It is now largely supplanted by swift-concurrency.
A few characteristics of operation queues that distinguish them from GCD dispatch queues:
Whereas dispatch queues always execute tasks in first-in, first-out order, operation queues take other factors into account when determining the execution order of tasks. Primary among these factors is whether a given task depends on the completion of other tasks. You configure dependencies when defining your tasks and can use them to create complex execution-order graphs for your tasks.
Operation queues can be used to manage dependencies between tasks that are, themselves, asynchronous (e.g., a network request). To wrap an asynchronous task in an
Operation
requires one to create a customOperation
subclass that performs the necessary KVO forisFinished
, etc. See theOperation
documentation.Operation queues are useful when attempting to control the degree of concurrency. Dispatch queues are either serial or concurrent, but offer no control over the degree of concurrency.
Operation
objects offer a richer mechanism to handle cancelation, whereby not only can a computational process periodically checkisCancelled
, but where relevant, you can override thecancel
method (e.g., to proactively cancel an asynchronous task wrapped in a customOperation
subclass).One can establish dependencies between
Operation
Oobjects.
The tasks you submit to an operation queue can either be a closure, a BlockOperation
, or an Operation
. An operation object is an object that encapsulates the work you want to perform and any data needed to perform it. Because the Operation
class is essentially an abstract base class, you typically define custom subclasses to perform your tasks. However, the Foundation framework does include some concrete subclasses that you can create and use as is to perform tasks.
Operation objects generate key-value observing (KVO) notifications, which can be a useful way of monitoring the progress of your task. Although operation queues always execute operations concurrently, you can use dependencies to ensure they are executed serially when needed.
Nowadays, if trying to schedule asynchronous tasks, one would consider swift-concurrency in lieu of an operation queue.
See also
OperationQueue
documentationOperation
documentation- The Concurrency Programming Guide