$npx -y skills add wshaddix/dotnet-skills --skill dotnet-csharp-async-patternsWriting async/await code. Task patterns, ConfigureAwait, cancellation, and common agent pitfalls.
| 1 | # dotnet-csharp-async-patterns |
| 2 | |
| 3 | Async/await best practices for .NET applications. Covers correct task usage, cancellation propagation, and the most common mistakes AI agents make when generating async code. |
| 4 | |
| 5 | Cross-references: [skill:dotnet-csharp-dependency-injection] for `IHostedService`/`BackgroundService` registration, [skill:dotnet-csharp-coding-standards] for `Async` suffix naming, [skill:dotnet-csharp-modern-patterns] for language-level features. |
| 6 | |
| 7 | --- |
| 8 | |
| 9 | ## Core Rules |
| 10 | |
| 11 | ### Always Async All the Way |
| 12 | |
| 13 | Every method in the async call chain must be `async` and `await`ed. Mixing sync and async causes deadlocks or thread pool starvation. |
| 14 | |
| 15 | ```csharp |
| 16 | // Correct: async all the way |
| 17 | public async Task<Order> GetOrderAsync(int id, CancellationToken ct = default) |
| 18 | { |
| 19 | var order = await _repo.GetByIdAsync(id, ct); |
| 20 | return order; |
| 21 | } |
| 22 | |
| 23 | // WRONG: blocking on async -- causes deadlocks in ASP.NET and UI contexts |
| 24 | public Order GetOrder(int id) |
| 25 | { |
| 26 | return _repo.GetByIdAsync(id).Result; // DEADLOCK RISK |
| 27 | } |
| 28 | ``` |
| 29 | |
| 30 | ### Prefer `Task` and `ValueTask` |
| 31 | |
| 32 | Return `Task` or `Task<T>` by default. Use `ValueTask<T>` when the method frequently completes synchronously (cache hits, buffered I/O) to avoid `Task` allocation. |
| 33 | |
| 34 | ```csharp |
| 35 | // ValueTask: frequently synchronous completion |
| 36 | public ValueTask<User?> GetCachedUserAsync(int id, CancellationToken ct = default) |
| 37 | { |
| 38 | if (_cache.TryGetValue(id, out var user)) |
| 39 | { |
| 40 | return ValueTask.FromResult<User?>(user); |
| 41 | } |
| 42 | |
| 43 | return LoadUserAsync(id, ct); |
| 44 | } |
| 45 | |
| 46 | private async ValueTask<User?> LoadUserAsync(int id, CancellationToken ct) |
| 47 | { |
| 48 | var user = await _repo.GetByIdAsync(id, ct); |
| 49 | if (user is not null) |
| 50 | { |
| 51 | _cache[id] = user; |
| 52 | } |
| 53 | |
| 54 | return user; |
| 55 | } |
| 56 | ``` |
| 57 | |
| 58 | **ValueTask rules:** |
| 59 | - Never `await` a `ValueTask` more than once |
| 60 | - Never use `.Result` or `.GetAwaiter().GetResult()` on an incomplete `ValueTask` |
| 61 | - If you need to await multiple times or pass it around, convert with `.AsTask()` |
| 62 | |
| 63 | --- |
| 64 | |
| 65 | ## Agent Gotchas |
| 66 | |
| 67 | These are the most common async mistakes AI agents make when generating C# code. |
| 68 | |
| 69 | ### 1. Blocking on Async (`.Result`, `.Wait()`, `.GetAwaiter().GetResult()`) |
| 70 | |
| 71 | ```csharp |
| 72 | // WRONG -- all of these can deadlock |
| 73 | var result = GetDataAsync().Result; |
| 74 | GetDataAsync().Wait(); |
| 75 | var result = GetDataAsync().GetAwaiter().GetResult(); |
| 76 | |
| 77 | // CORRECT |
| 78 | var result = await GetDataAsync(); |
| 79 | ``` |
| 80 | |
| 81 | The only safe place for `.GetAwaiter().GetResult()` is in `Main()` pre-C# 7.1 or in rare infrastructure code where async is impossible (static constructors, `Dispose()`). |
| 82 | |
| 83 | ### 2. `async void` |
| 84 | |
| 85 | `async void` methods cannot be awaited, and unhandled exceptions in them crash the process. |
| 86 | |
| 87 | ```csharp |
| 88 | // WRONG -- fire-and-forget, unobserved exceptions |
| 89 | async void ProcessOrder(Order order) |
| 90 | { |
| 91 | await _repo.SaveAsync(order); |
| 92 | } |
| 93 | |
| 94 | // CORRECT |
| 95 | async Task ProcessOrderAsync(Order order) |
| 96 | { |
| 97 | await _repo.SaveAsync(order); |
| 98 | } |
| 99 | ``` |
| 100 | |
| 101 | The **only** valid use of `async void` is event handlers (WinForms, WPF, Blazor `@onclick`), where the framework requires a `void` return type. |
| 102 | |
| 103 | ### 3. Missing `ConfigureAwait` |
| 104 | |
| 105 | In **library code**, use `ConfigureAwait(false)` to avoid capturing the synchronization context. In **application code** (ASP.NET Core, console apps), it is not needed because there is no synchronization context. |
| 106 | |
| 107 | ```csharp |
| 108 | // Library code |
| 109 | public async Task<byte[]> ReadFileAsync(string path, CancellationToken ct = default) |
| 110 | { |
| 111 | var bytes = await File.ReadAllBytesAsync(path, ct).ConfigureAwait(false); |
| 112 | return bytes; |
| 113 | } |
| 114 | |
| 115 | // Application code (ASP.NET Core) -- ConfigureAwait not needed |
| 116 | public async Task<IActionResult> GetOrder(int id, CancellationToken ct) |
| 117 | { |
| 118 | var order = await _service.GetOrderAsync(id, ct); |
| 119 | return Ok(order); |
| 120 | } |
| 121 | ``` |
| 122 | |
| 123 | ### 4. Fire-and-Forget Without Error Handling |
| 124 | |
| 125 | ```csharp |
| 126 | // WRONG -- exception is silently swallowed |
| 127 | _ = SendEmailAsync(order); |
| 128 | |
| 129 | // CORRECT -- use IHostedService or a background channel |
| 130 | await _backgroundQueue.EnqueueAsync(ct => SendEmailAsync(order, ct)); |
| 131 | ``` |
| 132 | |
| 133 | If fire-and-forget is truly necessary, at minimum log the exception: |
| 134 | |
| 135 | ```csharp |
| 136 | _ = Task.Run(async () => |
| 137 | { |
| 138 | try |
| 139 | { |
| 140 | await SendEmailAsync(order); |
| 141 | } |
| 142 | catch (Exception ex) |
| 143 | { |
| 144 | _logger.LogError(ex, "Failed to send email for order {OrderId}", order.Id); |
| 145 | } |
| 146 | }); |
| 147 | ``` |
| 148 | |
| 149 | ### 5. Forgetting `CancellationToken` |
| 150 | |
| 151 | Always accept and forward `CancellationToken`. Never silently drop it. |
| 152 | |
| 153 | ```csharp |
| 154 | // WRONG -- token not forwarded |
| 155 | public async Task<List<Order>> GetAllAsync(CancellationToken ct = default) |
| 156 | { |
| 157 | return await _dbContext.Orders.ToListAsync(); // missing ct! |
| 158 | } |
| 159 | |
| 160 | // CORRECT |
| 161 | public async Task<List<Order>> GetAllAsync(CancellationToken ct = default) |
| 162 | { |
| 163 | return await _dbContext.Orders.ToListAsync(ct); |
| 164 | } |
| 165 | ``` |
| 166 | |
| 167 | --- |
| 168 | |
| 169 | ## Cancellation Patterns |
| 170 | |
| 171 | ### Creating Linked Tokens |
| 172 | |
| 173 | Combine external cancellation with a timeout: |
| 174 | |
| 175 | ```csharp |
| 176 | public async Task<Result> ProcessWithTimeou |