Sobes.tech
Junior

In which thread are all controller operations performed?

sobes.tech AI

Answer from AI

Not all controller operations are performed on the same thread.

  • Most UI operations (interface updates, touch event handling) are executed on the main thread.
  • Operations that can block the main thread (e.g., sending network requests, processing large volumes of data, disk operations) should be performed on background threads.

Typical scenarios for using background threads:

  1. Grand Central Dispatch (GCD):
    DispatchQueue.global(qos: .userInitiated).async {
        // Long operations, such as network requests
        // After completing the background task, update the UI on the main thread
        DispatchQueue.main.async {
            // UI update
        }
    }
    
  2. Operation Queues:
    let queue = OperationQueue()
    queue.addOperation {
        // Long operations
        OperationQueue.main.addOperation {
            // UI update
        }
    }
    
  3. async/await (in Swift Concurrency):
    Task.detached(priority: .userInitiated) {
        // Long operations
        await MainActor.run {
            // UI update
        }
    }
    

Executing all operations on the main thread will block the interface (freeze the app), which will negatively affect the user experience.

In which thread are all controller operations… - sobes.tech