C# 14 cheatsheet

C# 14: Async, errors and resources

9 common C# 14 tasks.

Write an async method

Await I/O without blocking a thread. Async methods return Task or Task<T>.

async Task<string> GetAsync(HttpClient http, string url)
{
    return await http.GetStringAsync(url);
}

Run tasks in parallel

Start several tasks and wait for all of them.

var results = await Task.WhenAll(urls.Select(u => http.GetStringAsync(u)));

Support cancellation

Pass a CancellationToken so callers can stop long operations, for example on a timeout.

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var text = await http.GetStringAsync(url, cts.Token);

Handle exceptions

Catch specific exceptions, filter with when, and clean up in finally.

try
{
    Process(file);
}
catch (IOException ex) when (ex.HResult != 0)
{
    Console.Error.WriteLine(ex.Message);
}
finally
{
    Cleanup();
}

Dispose a resource automatically

A using declaration disposes the object at the end of the enclosing scope.

using var stream = File.OpenRead("data.bin");

Read and write files

Read and write text asynchronously.

var text = await File.ReadAllTextAsync("data.txt");
await File.WriteAllTextAsync("copy.txt", text);

Serialize to and from JSON

Convert objects to JSON text and back with System.Text.Json.

var json = JsonSerializer.Serialize(person);
var again = JsonSerializer.Deserialize<Person>(json);

Work with dates and times

DateOnly and TimeOnly model a date or a time of day on its own.

var today = DateOnly.FromDateTime(DateTime.UtcNow);
var nextWeek = today.AddDays(7);

Protect shared state

Use a lock to let only one thread run a block at a time.

private readonly Lock _gate = new();

lock (_gate)
{
    counter++;
}

Was this page helpful?