Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · C# · Chapter 09 / 10

Programming learning path

async/await, Task & concurrency basics

A Task represents an operation that may complete later. Marking a method async allows the use of await, but async does not automatically create a new thread.

What await changes

When an awaited operation is incomplete, the async method can return control to its caller rather than blocking until the operation finishes. The method continues later after the task completes. This is particularly useful for I/O such as HTTP, databases and file operations.

static async Task<int> GetStatusAsync(HttpClient client, string url)
{
    using var response = await client.GetAsync(url);
    return (int)response.StatusCode;
}

using var client = new HttpClient();
int status = await GetStatusAsync(client, "https://example.com");
Console.WriteLine(status);

Async is not parallelism

Asynchrony is mainly about not blocking while waiting. Parallelism is about executing CPU work simultaneously. An async method can run entirely without parallel execution.

Prefer Task or Task<T> as return types for async methods. async void is mainly for event handlers because a caller cannot normally await it or observe its exceptions through a returned task.

Key points

  • async does not automatically mean another thread.
  • await asynchronously waits for a Task and resumes when it completes.
  • .Result and .Wait() turn asynchronous flows into blocking waits and should not be the default approach.
  • Async and parallel are related concurrency concepts, but they solve different problems.

Source registry

1 chapter reference
Asynchronous programming with async and await

Task-based asynchronous programming, async and await

Microsoft Learn · Official documentation
Source ↗