Sobes.tech
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.

  1. async keyword: Marks a method as asynchronous. Such a method can contain the await operator.
  2. await keyword: Used before calling an asynchronous operation (usually a method returning Task or Task<T>). When execution reaches await, control returns to the calling method, and the freed thread can perform other work.
  3. Task / Task<T>: Represents a promise to complete an asynchronous operation and its result (for Task<T>). await "waits" for this "promise" to complete.
  4. State machine: The compiler transforms an asynchronous method into a finite automaton. This automaton saves the method's state when reaching await.
  5. 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.
  6. 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}"; 
}