ConcurrencyMidMCQ
What is a `Task` and how is it different from a `Thread`?
Test your knowledge:
Explanation & Code
Answer:
A Task is Swift's unit of async work. Unlike threads, tasks are lightweight, managed by the Swift runtime, and can be suspended without blocking an underlying thread.
Task | Thread | |
|---|---|---|
| Cost | Lightweight | Heavy (~512KB stack) |
| Managed by | Swift runtime | OS |
| Suspension | Yes (non-blocking) | No (blocks thread) |
| Cancellation | Built-in | Manual |
Code Example:
// Creating a task
let task = Task {
let data = try await fetchData()
await MainActor.run { updateUI(with: data) }
}
// Cancelling it
task.cancel()
// Task inherits priority and actor context from where it's created
// Use Task.detached to explicitly break that inheritance
Task.detached(priority: .background) {
await expensiveBackgroundWork()
}
Rate your understanding: