Sobes.tech
Junior

Mis on dispatch grupp?

sobes.tech AI

Vastus AI-lt

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

Main methods:

  • enter(): Increases the task counter in the group. Called before starting an asynchronous task.
  • leave(): Decreases the task counter 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 counter in the group reaches zero.
  • wait(): Blocks the current thread until the task counter in the group reaches zero. Use with caution to avoid blocking the main thread.

Usage example:

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 with wait() in case of synchronous waiting (not recommended in UI applications)
Thread.sleep(forTimeInterval: 3)