Skip to content

Asynchronous Programming

Sann Lynn Htun edited this page Nov 19, 2024 · 1 revision

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

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        int result = await CalculateAsync();
        Console.WriteLine($"Calculation result: {result}");
    }

    static async Task<int> CalculateAsync()
    {
        await Task.Delay(2000); // Simulates a delay
        return 42; // Returns a result
    }
}

Exception Handling

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            await PerformAsyncOperation();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex.Message}");
        }
    }

    static async Task PerformAsyncOperation()
    {
        await Task.Delay(2000);
        throw new InvalidOperationException("An error occurred.");
    }
}

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.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await foreach (var number in GenerateNumbersAsync())
        {
            Console.WriteLine(number);
        }
    }

    static async IAsyncEnumerable<int> GenerateNumbersAsync()
    {
        for (int i = 1; i <= 5; i++)
        {
            await Task.Delay(1000); // Simulates delay
            yield return i;
        }
    }
}

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.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally