Asynchronous Programming

C# Asynchronous Programming

Asynchronous programming in C# allows tasks to run concurrently, improving performance and responsiveness, especially for I/O-bound operations.

Key Concepts

  1. async and await Keywords

Enable asynchronous methods and task completion without blocking the main thread.

Examples

Basic Example

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Starting asynchronous operation...");
        await PerformAsyncOperation();
        Console.WriteLine("Asynchronous operation completed.");
    }

    static async Task PerformAsyncOperation()
    {
        Console.WriteLine("Working...");
        await Task.Delay(2000); // Simulates a delay
        Console.WriteLine("Done.");
    }
}

Example with Return Value

Exception Handling

Advanced Features

  1. Task and Task

Represent asynchronous operations, with Task<T> returning a value of type T.

  1. Parallel Programming

Using Task.WhenAll and Task.WhenAny to perform multiple tasks simultaneously.

  1. Asynchronous Streams

Use IAsyncEnumerable<T> and await foreach for asynchronous data streams.

Summary

  • async and await: Enable asynchronous operations.

  • Task and Task: Handle asynchronous methods, optionally returning values.

  • Exception Handling: Use try-catch for asynchronous methods.

  • Advanced Techniques: Parallel tasks and asynchronous streams for efficient data handling.

C# asynchronous programming enhances application performance and responsiveness, making it ideal for modern, high-performance applications.