Sobes.tech
Middle

What methods exist for placing tasks in the Grand Central Dispatch (GCD) queue?

sobes.tech AI

Answer from AI

The following methods exist for scheduling tasks in the GCD queue:

  1. Asynchronous execution (async): The task is added to the queue, and execution immediately continues on the current thread without waiting for the task in the queue to finish.

    DispatchQueue.global().async {
        // Task code
    }
    
  2. Synchronous execution (sync): The task is added to the queue, and the current thread is blocked until the task in the queue completes. Avoid using sync on the main thread for long-running tasks to prevent blocking the UI.

    DispatchQueue.global().sync {
        // Task code, the current thread will wait
    }
    
  3. Delayed execution (asyncAfter): The task is added to the queue with a specified delay. Execution will start no earlier than the specified time.

    DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
        // Task code will execute after 2 seconds
    }
    
  4. Execution in a group (DispatchGroup): Tasks can be added to a DispatchGroup for synchronization of their completion. You can wait for all to finish or be notified (notify) after they complete.

    let group = DispatchGroup()
    
    group.enter()
    DispatchQueue.global().async {
        // Task 1
        group.leave()
    }
    
    group.enter()
    DispatchQueue.global().async {
        // Task 2
        group.leave()
    }
    
    group.notify(queue: .main) {
        // All tasks in the group are finished
    }
    
  5. Applying iterations (concurrentPerform): Allows executing a given block of code iterations times in parallel on a concurrent queue.

    DispatchQueue.concurrentPerform(iterations: 100) { index in
        // Code executed for each index in parallel
    }
    
  6. DispatchWorkItem: Wraps a block of code and allows canceling the task before it starts or after it has been added to the queue if it hasn't started yet.

    var workItem: DispatchWorkItem?
    
    workItem = DispatchWorkItem {
        // Task code
    }
    
    DispatchQueue.global().async(execute: workItem!)
    
    // You can cancel the task if it hasn't started yet
    // workItem?.cancel()
    
What methods exist for placing tasks in the Grand… - sobes.tech