Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Code
using System;
using System.Net.Http;
using System.Threading.Tasks;
HttpClient client = new();
async Task<string> FetchAsync(string url, CancellationToken ct = default)
{
using var resp = await client.GetAsync(url, ct);
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsStringAsync(ct);
}
async Task RunAsync()
{
try
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
// Run requests in parallel
var tasks = new[]
{
FetchAsync("https://api.github.com", cts.Token),
FetchAsync("https://httpbin.org/get", cts.Token),
};
string[] results = await Task.WhenAll(tasks);
Console.WriteLine($"got {results.Length} responses");
}
catch (HttpRequestException ex)
{
Console.Error.WriteLine($"HTTP error: {ex.Message}");
}
}
await RunAsync();Explanation
async marks a method as one that can await other async operations, returning a Task that represents the in-flight work. await suspends the method without blocking the thread, yielding control back to the caller until the awaited task completes. Task.WhenAll composes multiple tasks so they run concurrently and waits for all of them together.
More C# Snippets
LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
Properties
Encapsulate state with auto, computed, validated, and init-only properties.
Generics
Write type-parameterized methods and classes with constraints.
Delegates and Events
Define delegate types and publish events with safe subscription.
Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.
Collections
Use List, Dictionary, HashSet, Queue, Stack, and read-only views.