C# Async & Await
Asynchronous Programming in C#
The core of async programming is the Task and Task<T> objects, which model asynchronous operations. These are supported by the async and await keywords, allowing non-blocking executions.
Asynchronous operations allow your applications to remain responsive while running long-lived background jobs like database reads or network calls, rather than blocking the main thread.
When an await expression is encountered, the current method yields execution, and the runtime schedules the remainder of the method on a thread pool thread once the task completes.
C# also supports task combinators like Task.WhenAll() to run multiple asynchronous operations in parallel, returning only when all of them complete, optimizing throughput.
Parallel Task Executions
Using Task.WhenAll(t1, t2) compiles multiple separate async tasks and yields control until they have all finished running in parallel.
using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
Task t1 = Task.Delay(100);
Task t2 = Task.Delay(200);
await Task.WhenAll(t1, t2);
Console.WriteLine("Parallel Tasks completed!");
}
}using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
Console.WriteLine("Main thread starting task...");
await Task.Delay(500);
Console.WriteLine("Task complete!");
}
}