DispatchQueue
An object that manages the execution of tasks serially or concurrently on your app’s main thread or on a background thread.
Declaration
class DispatchQueueOverview
Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system. Except for the dispatch queue representing your app’s main thread, the system makes no guarantees about which thread it uses to execute a task.
You schedule work items synchronously or asynchronously. When you schedule a work item synchronously, your code waits until that item finishes execution. When you schedule a work item asynchronously, your code continues executing while the work item runs elsewhere.
Avoiding Excessive Thread Creation
When designing tasks for concurrent execution, do not call methods that block the current thread of execution. When a task scheduled by a concurrent dispatch queue blocks a thread, the system creates additional threads to run other queued concurrent tasks. If too many tasks block, the system may run out of threads for your app.
Another way that apps consume too many threads is by creating too many private concurrent dispatch queues. Because each dispatch queue consumes thread resources, creating additional concurrent dispatch queues exacerbates the thread consumption problem. Instead of creating private concurrent queues, submit tasks to one of the global concurrent dispatch queues. For serial tasks, set the target of your serial queue to one of the global concurrent queues. That way, you can maintain the serialized behavior of the queue while minimizing the number of separate queues creating threads.
Topics
Creating a Dispatch Queue
mainglobal(qos:)init(label:qos:attributes:autoreleaseFrequency:target:)DispatchQoS.QoSClassDispatchQueue.AttributesDispatchQueue.AutoreleaseFrequencyOS_dispatch_queue_mainOS_dispatch_queue_globalDispatchSerialQueueDispatchConcurrentQueuedispatch_queue_main_tdispatch_queue_global_tdispatch_queue_serial_tdispatch_queue_concurrent_t
Executing Tasks Asynchronously
async(execute:)asyncAfter(deadline:execute:)asyncAfter(deadline:qos:flags:execute:)asyncAfter(wallDeadline:execute:)asyncAfter(wallDeadline:qos:flags:execute:)
Executing Tasks Synchronously
Executing a Task in Parallel
Dispatching Work to Groups
Managing Queue Attributes
Getting and Setting Contextual Data
Managing the Main Dispatch Queue
Scheduling Combine Publishers
Deprecated
Instance Methods
asyncAfterUnsafe(deadline:qos:flags:execute:)asyncAfterUnsafe(wallDeadline:qos:flags:execute:)asyncAndWait(execute:)asyncAndWait(execute:)asyncAndWait(flags:execute:)asyncUnsafe(group:qos:flags:execute:)