Async and Await
Prerequisites: File I/O
async/await let code that waits on something slow (a network
call, a file read) do so without blocking the calling thread —
directly parallel to JavaScript's async/await.
async Task<string> FetchDataAsync() {
using var client = new HttpClient();
return await client.GetStringAsync("https://api.example.com/data");
}
async Task Main() {
Console.WriteLine("Starting...");
string data = await FetchDataAsync();
Console.WriteLine(data);
}
A method marked async returns a Task (or Task<T>) — a
placeholder for a result that isn't ready yet, exactly like a
JavaScript Promise. await pauses that method (without blocking
the thread) until the Task completes.
Common mistakes
- Calling
.Resultor.Wait()on aTaskinstead ofawaiting it — this blocks the calling thread and can cause a deadlock in some contexts (notably older ASP.NET and UI applications). - Forgetting
awaiton anasynccall entirely — the call starts but the calling code moves on without its result, and any exception it throws goes unobserved.