Core Features

Async/Await

Write non-blocking code with C#'s async/await pattern for responsive applications.

Why Async?

Synchronous code blocks the thread while waiting for I/O (disk, network, database). Async code releases the thread to do other work while waiting.

async/await Keywords

  • async: Marks a method as asynchronous
  • await: Suspends execution until the awaited task completes
  • Task: Represents an ongoing operation (like Promise in JS)
  • Task<T>: Async operation that returns a value

Best Practices

  • Return Task or Task<T> (not void) from async methods
  • Use await instead of .Result (avoids deadlocks)
  • Use Task.WhenAll for parallel operations
  • Suffix async methods with Async

Example

csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;

public class WeatherService {
    private readonly HttpClient _client;

    public WeatherService(HttpClient client) {
        _client = client;
    }

    // Async method returns Task<string>
    public async Task<string> GetWeatherAsync(string city) {
        string url = $"https://api.weather.com/{city}";
        string response = await _client.GetStringAsync(url);
        return response;
    }

    // Multiple async operations in sequence
    public async Task<(string, string)> GetTwoCitiesAsync() {
        string london = await GetWeatherAsync("london");
        string paris = await GetWeatherAsync("paris");
        return (london, paris);
    }

    // Parallel async operations (faster!)
    public async Task<string[]> GetMultipleCitiesAsync(string[] cities) {
        Task<string>[] tasks = Array.ConvertAll(cities, GetWeatherAsync);
        return await Task.WhenAll(tasks);
    }
}

// Error handling
public async Task<bool> TrySaveDataAsync(string data) {
    try {
        await SaveToFileAsync(data);
        await NotifyApiAsync(data);
        return true;
    } catch (HttpRequestException ex) {
        Console.WriteLine($"Network error: {ex.Message}");
        return false;
    } catch (Exception ex) {
        Console.WriteLine($"Error: {ex.Message}");
        return false;
    }
}

// Cancellation token for timeout/cancel support
public async Task<string> GetDataWithTimeoutAsync(
    CancellationToken cancellationToken = default) {
    using var client = new HttpClient();
    string result = await client
        .GetStringAsync("https://api.example.com/data", cancellationToken);
    return result;
}

// Entry point
async Task Main() {
    using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
    try {
        // await GetDataWithTimeoutAsync(cts.Token);
        Console.WriteLine("Done!");
    } catch (OperationCanceledException) {
        Console.WriteLine("Timed out!");
    }
}
Try it yourself — CSHARP