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
asyncdoes not automatically mean another thread.awaitasynchronously waits for a Task and resumes when it completes..Resultand.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.