How does async/await work in C#?
async/await enables asynchronous programming without blocking a thread. Marking a method async lets you await a Task or Task<T>, and the compiler rewrites the method into a state machine. When the awaited operation is incomplete, control returns to the caller and resumes via a continuation when it completes.
public async Task<string> FetchAsync(HttpClient client, string url) {
string body = await client.GetStringAsync(url);
return body.Trim();
}
var text = await FetchAsync(client, url);
Key points: async void is only for event handlers, because callers cannot catch its exceptions or await it. Return Task when there is no value. Do not block on async code with .Result or .Wait(), which can deadlock. Use ConfigureAwait(false) in library code to avoid capturing the synchronisation context. I/O-bound work benefits most; CPU-bound work belongs on Task.Run.