# C# Async and Concurrency Apply these rules when adding or changing asynchronous APIs, background work, or concurrent processing. * Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks. * Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock. * Return `Task` or `ValueTask` from async methods. Use `async void` only for event handlers, because callers cannot await it and its exceptions escape to the synchronization context; catch and handle failures inside such handlers. * Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller. * In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread. * Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`. * Use `ValueTask` only when profiling supports it. Await a `ValueTask` exactly once, never concurrently, and never read `.Result` before it completes; otherwise prefer `Task`. * Keep shared state safe under concurrent access and preserve cancellation and exception behavior when coordinating tasks. Prefer immutable messages or synchronization primitives with clear ownership over unsynchronized shared mutation. * For synchronous locks on .NET 9+, prefer `System.Threading.Lock` over locking on `object`. Use `SemaphoreSlim` when a critical section contains `await`. Avoid blocking thread-pool threads and starting background work whose lifetime is detached from its owner. * For producer/consumer work, use `Channel.CreateBounded` so a fast producer gets backpressure and cannot exhaust memory. * Retry only transient failures, with bounded attempts and delay, in one layer only. Prefer the project's resilience library (`Microsoft.Extensions.Http.Resilience` or Polly v8) over hand-written loops. Preserve idempotency and cancellation. * Create `HttpClient` through `IHttpClientFactory` or reuse a long-lived instance with `SocketsHttpHandler.PooledConnectionLifetime`; never create one per request.