| Task Parallel Library (TPL) in C# | Functional Programming in C# | |
⏳ Asynchronous Programming in C# |
async and await in C#Asynchronous programming with async and await is a powerful, modern feature in C# that simplifies writing code for non-blocking operations. Introduced in C# 5.0, this model is part of the Task-based Asynchronous Pattern (TAP) and improves the responsiveness and scalability of applications—especially during I/O-bound tasks.
In a synchronous program, a time-consuming operation (like downloading a large file or querying a database) will block the executing thread. The application becomes unresponsive until the operation completes. In a UI application, this causes the program to freeze; in a server app, it ties up valuable thread pool resources.
async and awaitThe async and await keywords allow you to write code that looks sequential and readable but executes in a non-blocking way.
async keyword: Marks a method as asynchronous. It typically returns a Task or Task<TResult>, representing ongoing work.await keyword: Suspends execution until the awaited Task completes—without blocking the thread. Control is returned to the caller, and execution resumes when the task finishes.await expression (usually an I/O-bound operation).Task to its caller, and the thread is freed.await point.
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class AsyncExample
{
// The 'async' keyword allows 'await' to be used in this method.
public static async Task DownloadPageAsync()
{
Console.WriteLine("Starting download... (Thread ID: " + Thread.CurrentThread.ManagedThreadId + ")");
using var client = new HttpClient();
// The 'await' keyword suspends execution here and frees the thread.
string content = await client.GetStringAsync("http://www.example.com");
// Execution resumes here after download completes.
Console.WriteLine("\nDownload complete! (Thread ID: " + Thread.CurrentThread.ManagedThreadId + ")");
Console.WriteLine($"Downloaded content length: {content.Length}");
}
public static async Task Main()
{
Task downloadTask = DownloadPageAsync();
Console.WriteLine("Main method is doing other work... (Thread ID: " + Thread.CurrentThread.ManagedThreadId + ")");
// Simulate concurrent work
for (int i = 0; i < 5; i++)
{
Console.Write(".");
await Task.Delay(200);
}
// Wait for the download to complete
await downloadTask;
Console.WriteLine("\nMain method finished.");
}
}
Use code with caution.
Asynchronous programming allows your application to perform tasks like I/O operations, network calls, or file access without blocking the main thread. In C#, this is achieved using the async and await keywords.
The async/await pattern was introduced in C# 5.0 with the release of .NET Framework 4.5.
async marks a method as asynchronous.await pauses execution until the awaited task completes.Task or Task<T>.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program {
static async Task Main() {
Console.WriteLine("Starting download...");
HttpClient client = new HttpClient();
string html = await client.GetStringAsync("https://example.com");
Console.WriteLine($"Downloaded {html.Length} characters.");
}
}
async for I/O-bound operations (e.g., file, network)..Result or .Wait()—they block threads.ConfigureAwait(false) in library code to avoid deadlocks.Task.WhenAll() to run multiple tasks concurrently.try-catch inside async methods.Task.Run() or Parallel.
Asynchronous programming with async and await is essential for building modern, responsive, and scalable applications in C#. It simplifies complex workflows and helps you write clean, maintainable code.
await.async Task, not async void: Except for event handlers, always return Task or Task<TResult>..Result or .Wait() in async code—they can cause deadlocks.DownloadPageAsync).ConfigureAwait(false) in libraries: Improves performance and avoids capturing synchronization context.The async/await model allows developers to write clear, maintainable, and responsive code for asynchronous operations. It keeps apps fast and responsive, avoids blocking threads, and integrates seamlessly with the Task Parallel Library (TPL). When used correctly, it makes asynchronous programming in C# both elegant and efficient.
| Task Parallel Library (TPL) in C# | Functional Programming in C# | |