Middle
How does the async/await mechanism work in C#?
sobes.tech AI
Answer from AI
The async/await mechanism allows writing asynchronous code that looks like synchronous code.
asynckeyword: Marks a method as asynchronous. Such a method can contain theawaitoperator.awaitkeyword: Used before calling an asynchronous operation (usually a method returningTaskorTask<T>). When execution reachesawait, control returns to the calling method, and the freed thread can perform other work.Task/Task<T>: Represents a promise to complete an asynchronous operation and its result (forTask<T>).await"waits" for this "promise" to complete.- State machine: The compiler transforms an asynchronous method into a finite automaton. This automaton saves the method's state when reaching
await. - Continuation: When the awaited task completes, the runtime schedules the remaining part of the asynchronous method (the continuation) on a thread from the thread pool or on the same synchronization context if it is captured.
- Control return: After the asynchronous operation completes, control returns to the point after
await, and the method continues with the saved state.
// Asynchronous method
async Task<int> GetLengthAsync(string url)
{
// Create an HTTP client
using var client = new HttpClient();
// Perform an asynchronous request to the URL
// Await waits for the request to complete without blocking the thread
string content = await client.GetStringAsync(url);
// Continuation executes after content is received
return content.Length;
}
// Using the asynchronous method
async void Button_Click(object sender, EventArgs e)
{
// Await waits for GetLengthAsync to complete
// UI thread is not blocked
int length = await GetLengthAsync("https://example.com");
// Update UI element
Label1.Text = $"Content length: {length}";
}