-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
A task represents a unit of work that can be run asynchronously and provide an alternative to dispatch queues. Tasks enable functions to run concurrently without blocking the main thread, similar to what we just saw with the async and await keywords however tasks give us additional control.
To create a task with use the task initializer which takes a closure containing the code to execute asynchronously. This is the syntax to create a task:
Task {
//asynchronous code here
}
One thing to keep I mind is using the task API does not necessarily create a new thread. Instead tasks leverages Swift’s concurrency model which uses cooperative thread management. When a task is created using async let or await, Swift manages the execution of these tasks within the same thread or across different threads managed by the system. It doesn't guarantee the creation of a new thread for each new task. When a Task is created using Task { }, it runs the provided code asynchronously...