Sobes.tech
Junior

What is a dispatch group?

sobes.tech AI

Answer from AI

Dispatch Group is a mechanism in the Grand Central Dispatch (GCD) framework that allows you to group tasks and receive a notification when all tasks in the group are completed.

Main methods:

  • enter(): Increases the task count in the group. Called before starting an asynchronous task.
  • leave(): Decreases the task count in the group. Called after completing an asynchronous task.
  • notify(queue:execute:): Registers a block of code to be executed on the specified queue after the task count in the group reaches zero.
  • wait(): Blocks the current thread until the task count in the group reaches zero. Should be used with caution to avoid blocking the main thread.

Example usage:

import Foundation

let group = DispatchGroup()
let queue = DispatchQueue.global()

queue.async(group: group) {
    // Task 1
    print("Task 1 is running")
    Thread.sleep(forTimeInterval: 2)
    print("Task 1 completed")
}

queue.async(group: group) {
    // Task 2
    print("Task 2 is running")
    Thread.sleep(forTimeInterval: 1)
    print("Task 2 completed")
}

group.notify(queue: DispatchQueue.main) {
    // This block will execute after all tasks are finished
    print("All tasks are completed")
}

// To prevent the main thread from finishing immediately. In a real application, this is managed by a RunLoop
// Or wait() in case of synchronous waiting (not recommended in UI applications)
Thread.sleep(forTimeInterval: 3)
What is a dispatch group? — iOS - sobes.tech