C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Async and Await

C# Async and Await

async/await lets you write asynchronous code that looks like synchronous code — no callbacks, no manual thread management.

1 - Basic async Method

public static async Task<string> FetchDataAsync(string url)
{
    using var client = new HttpClient();
    string data = await client.GetStringAsync(url);
    return data;
}

// Call it
string result = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(result);

2 - async void vs async Task

// async Task — preferred: awaitable, exceptions propagate
public async Task DoWorkAsync()
{
    await Task.Delay(1000); // simulates async work
    Console.WriteLine("Work done.");
}

// async void — only for event handlers!
private async void Button_Click(object sender, EventArgs e)
{
    await DoWorkAsync();
}

3 - Task.WhenAll — Parallel Async

public static async Task RunParallelAsync()
{
    Task<int> t1 = Task.Run(() => { Thread.Sleep(1000); return 1; });
    Task<int> t2 = Task.Run(() => { Thread.Sleep(1000); return 2; });
    Task<int> t3 = Task.Run(() => { Thread.Sleep(1000); return 3; });

    // All three run concurrently — total time ~1 sec, not 3
    int[] results = await Task.WhenAll(t1, t2, t3);
    Console.WriteLine(results.Sum()); // 6
}

4 - Cancellation

public static async Task LongOperationAsync(CancellationToken ct)
{
    for (int i = 0; i < 100; i++)
    {
        ct.ThrowIfCancellationRequested();
        await Task.Delay(100, ct);
        Console.WriteLine($"Step {i}");
    }
}

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try
{
    await LongOperationAsync(cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Cancelled after 3 seconds.");
}

Note: Never use Task.Result or Task.Wait() in async code — they block the thread and can cause deadlocks, especially in UI or ASP.NET contexts. Always use await instead.

-Tip-

C# {"id":48,"topic_id":3,"name":"C# Async Programming","slug":"c-async-programming","image":null,"description":"<p>Write non-blocking code with async\/await, Task, and the Task Parallel Library.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":17,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: