
async/await Doesn't Create Threads: What Really Happens
- كاتب موثّق
- .NET 10
محتويات المقال
BuildReport became async Task<string> BuildReportAsync, the click handler now awaits it, and the pull request says "moved report generation to a background thread." The window still freezes exactly as long as before. Nothing moved anywhere. The method still hashes and formats the export on the UI thread, because async never asked for another thread in the first place.
The common misconception
async makes it run in the background, on a new or separate thread, so the caller is never held up. Calling it starts a parallel job, and await waits for that job to finish.
async and await, the usual way to keep a UI responsive was a BackgroundWorker or a Thread, so asynchrony and extra threads came as a pair. Tutorials often show async next to Task.Run, which really does use another thread. And if you log thread IDs in a console app, the code after an await often runs on a different thread than the code before it, which looks like proof.
async and await keywords don't cause extra threads to be created. The thread you see after an await was borrowed, and the code before the first real wait never left the caller's thread.
What actually happens
async changes how the method is compiled
async changes how the method is compiledasync is an instruction to the compiler, not to a scheduler. It allows await in the body, and the compiler rewrites the method as a state machine: a small generated type that keeps the locals the method needs later and remembers which await it reached. Calling the method starts that state machine right away, on the calling thread, like any other call. It keeps running there until it awaits something that isn't finished yet. A method that never reaches such an await runs synchronously from start to end, whatever its signature says.
await is a point where the method may pause
await is a point where the method may pauseawait, the method first checks whether the awaited task has already completed. If it has, the method takes the result and keeps going without pausing. If not, it registers the rest of the method as a , saves its state, and returns. In Release builds this is the moment the state machine, a struct until now, is copied to the heap. The caller receives an unfinished Task and carries on, or awaits it and returns to its own caller in turn. On a UI thread, that return is what lets the window keep processing clicks and repainting.
While it waits, no thread waits with it
Where the rest of the method runs
await captures the current . WPF and WinForms install one that posts the continuation back to the UI thread, so the code after an await can update controls safely. ASP.NET Core and console apps have none, so the continuation usually runs as part of completing the task, on a thread:
Console.WriteLine($"Before: thread {Environment.CurrentManagedThreadId}");await Task.Delay(500); // no thread is blocked during these 500 msConsole.WriteLine($"After: thread {Environment.CurrentManagedThreadId}");// In a console app the two IDs usually differ: the pool lent a threadasync.
Real threads come from somewhere else
async can't hand that work to another thread; you have to ask for one. Here's a console version of the same code, before and after:
using System.Security.Cryptography;var data = new byte[200_000_000];Task<string> export = ExportAsync(data);Console.WriteLine("Back in the caller"); // printed only after the hashingawait export;static async Task<string> ExportAsync(byte[] data){ // async moved nothing: this runs on the caller's thread string hash = Convert.ToHexString(SHA256.HashData(data)); await File.WriteAllTextAsync("export.sha256", hash); // first await return hash;}using System.Security.Cryptography;var data = new byte[200_000_000];Task<string> export = ExportAsync(data);Console.WriteLine("Back in the caller"); // printed right awayawait export;static async Task<string> ExportAsync(byte[] data){ // CPU-bound work: ask the thread pool for a thread explicitly string hash = await Task.Run( () => Convert.ToHexString(SHA256.HashData(data))); await File.WriteAllTextAsync("export.sha256", hash); return hash;}ExportAsync reaches its first await, so "Back in the caller" appears only when all the work is done. In the second, Task.Run queues the hashing to the thread pool, and the await on that unfinished task returns control at once. In the desktop app, that one change is what unfreezes the window.
Myth vs reality
async runs the method on a background thread | await that has to wait |
await blocks until the task finishes | Task to the caller and frees the thread |
await means async created it | |
async makes CPU-heavy code non-blocking | Task.Run |
How to apply it in your project
Find async methods that never really wait Look for asyncmethods with noawait, or whose onlyawaitcomes after the expensive part. Everything up to that point runs on the caller's thread. Make the slow part truly asynchronous, or treat the method as the synchronous method it is.Classify each slow operation Waiting on a network, disk or database is I/O-bound: call the real async API, such as GetStringAsync,ToListAsyncorReadAsync, and await it withoutTask.Run. Computing something is CPU-bound: in a UI app, wrap it inTask.Runat the call site, the event handler, rather than inside a library method.Don't tie state to a thread After an await, the code may continue on a different thread. Don't keep per-request data in[ThreadStatic]fields or assume the thread ID stays the same. Pass data as parameters, or useAsyncLocal<T>when you really need ambient data.Await instead of blocking .Resultand.Wait()turn a freed thread back into a blocked one, and on a UI thread they can deadlock. Await all the way up to the event handler or the endpoint.
Key takeaways
asynclets a method useawait; it doesn't create, request or switch threads.An async method runs synchronously on the caller's thread until the first awaitthat has to wait, then returns an unfinishedTask.While an I/O operation is pending, no thread is blocked on it, which is how a few threads can serve many requests. The code after an awaitruns where the captured context sends it: the UI thread, or a thread pool thread when there's no context.CPU-bound work needs a thread you ask for, with Task.Runin UI apps; in ASP.NET Core,Task.Runplusawaitonly adds overhead.
📚 المصادر
The Task Asynchronous Programming (TAP) model with async and await — Microsoft Learn Asynchronous programming with async and await — Microsoft Learn How Async/Await Really Works in C# — Stephen Toub, .NET Blog ConfigureAwait FAQ — Stephen Toub, .NET Blog ASP.NET Core Best Practices: Avoid blocking calls — Microsoft Learn
التعليقات (0)