Which thread does async/await use when called inside a method launched with Task?
sobes.tech AI
Answer from AI
When using async/await inside a method launched with Task in iOS (for example, using Swift Concurrency), the execution of asynchronous code occurs in a context managed by the task scheduler.
The async/await itself does not bind the code to a specific thread. Instead, when awaiting, the current thread can be released for other tasks, and the continuation of the method after await can run on any available thread from the thread pool or on the same thread if possible.
Thus, the thread on which the code after await runs is not guaranteed and depends on the scheduler. This allows efficient resource utilization and prevents blocking the main thread (e.g., the UI thread).
Example:
Task {
print("Start on thread: \(Thread.current)")
await someAsyncFunction()
print("Continue on thread: \(Thread.current)")
}
The output may show different threads before and after await.