Development Playbook

Make the build reject the async mistakes agents write in C#

Roslyn and threading analyzers turned into a gate the agent can't argue with: dropped cancellation tokens, fire-and-forget calls, async void and blocking waits fail the build. About 15 minutes to set up.

A massive concrete wall with one narrow gate at its base and a band of warm light spilling across a dark stone floor

An agent adds an endpoint that calls a rates service. The code compiles, the happy-path test passes and the diff looks tidy. Three weeks later a deploy drains slowly because every in-flight request to that service ignores the client’s disconnect, and a background audit call has been throwing unobserved exceptions into the void since day one.

None of that is exotic. It is the same four or five async mistakes, and generated C# makes them often, because each one compiles cleanly and reads fine in a diff. A human reviewer can catch them, but a compiler can catch them every time and without getting tired.

This Playbook sets up a build that fails on those mistakes, a small script that stops the agent from “fixing” the failure by weakening the rules, and a prompt that makes the agent loop until the build is clean. It works with any coding agent that can read files and run a shell, because the gate is dotnet build and a bash script, and the check that proves it worked is an exit code.

What the defaults leave on the table

The .NET SDK ships the Roslyn analyzers, and for projects targeting .NET 5 or later they run without any setup. The catch is how few of them are loud. Microsoft’s code analysis overview says that in the default analysis mode only a small number of rules are enabled as build warnings, and the rest are suggestions or off.

The rules that matter here are in the quiet group on .NET 10. According to their docs pages, CA2016 (forward the CancellationToken) is enabled only as a suggestion, and CA1849 (call async methods when in an async method) and CA1305 (specify IFormatProvider) aren’t enabled at all. A suggestion shows up as a grey squiggle in an editor and never in a CI log, which is exactly where an agent working in a terminal is looking.

The other half is the Visual Studio threading analyzers, a separate package from Microsoft. Its rules VSTHRD002 (problematic synchronous waits), VSTHRD100 (async void) and VSTHRD110 (observe the result of async calls) default to Warning, per the project’s rules index. A warning an agent can see is still a warning it can ignore.

So the job is to promote a short list of rules to errors, and then protect that list.

The code under test

Start with a minimal ASP.NET Core project and the package:

dotnet new web -n Orders -o Orders --framework net10.0
cd Orders
dotnet add package Microsoft.VisualStudio.Threading.Analyzers

The project targets net10.0. The package restored at 18.12.1, and the SDK was 10.0.115.

Here’s the endpoint, the way an agent typically leaves it. The handler is fine. The client behind it is where the problems sit:

// Program.cs
using Orders;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.Services.AddSingleton<RateClient>();
var app = builder.Build();

app.MapGet("/quote/{id}", async (string id, RateClient rates, CancellationToken ct) =>
{
    var rate = await rates.GetRateAsync(id, ct);
    return Results.Ok(new { id, rate });
});

app.Run();
// RateClient.cs
namespace Orders;

public sealed class RateClient(IHttpClientFactory factory)
{
    public async Task<decimal> GetRateAsync(string id, CancellationToken ct)
    {
        var http = factory.CreateClient();
        var text = await http.GetStringAsync($"https://rates.example/{id}");
        AuditAsync(id);
        return decimal.Parse(text);
    }

    public decimal GetRateBlocking(string id)
    {
        return GetRateAsync(id, CancellationToken.None).Result;
    }

    public async void Refresh(string id)
    {
        await GetRateAsync(id, CancellationToken.None);
    }

    private static async Task AuditAsync(string id)
    {
        await Task.Delay(10);
        Console.WriteLine($"audit {id}");
    }
}

Five defects in a few lines, and a plain dotnet build on the default settings reports three warnings and no error. The ct that the handler passes in is received and then dropped on the way to GetStringAsync. AuditAsync is fire-and-forget. GetRateBlocking blocks a thread on .Result. Refresh is async void, so an exception in it takes the process down. And decimal.Parse(text) uses whatever culture the server happens to run under, so the string 1.5 parses as 1.5 under en-GB and as 15 under de-DE, where the full stop is a group separator. Nothing throws, and the number is simply wrong.

The gate: three files

Put these at the solution root, next to the .csproj folders.

Directory.Build.props raises the analysis level for every project and turns the one compiler warning that matters into an error:

<Project>
  <PropertyGroup>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
    <WarningsAsErrors>$(WarningsAsErrors);CS4014</WarningsAsErrors>
  </PropertyGroup>
</Project>

CS4014 is the compiler’s own “this call is not awaited” warning. It’s the fire-and-forget catcher, and it’s a warning by default. latest-recommended is the compound AnalysisLevel form from the code analysis docs: the recommended rule set for the newest rules the SDK ships. It adds more warnings than the list below turns into errors, which is deliberate (see the failure modes).

.editorconfig is the short list of rules that fail the build:

root = true

[*.cs]
# Cancellation: pass the caller's token down
dotnet_diagnostic.CA2016.severity = error
# Blocking inside async code
dotnet_diagnostic.CA1849.severity = error
dotnet_diagnostic.CA2012.severity = error
# Threading analyzers
dotnet_diagnostic.VSTHRD002.severity = error
dotnet_diagnostic.VSTHRD100.severity = error
dotnet_diagnostic.VSTHRD110.severity = error
# Culture-sensitive parsing and formatting
dotnet_diagnostic.CA1305.severity = error

dotnet_diagnostic.<ID>.severity is the documented way to set a rule’s severity. CA2012 is the rule for a ValueTask consumed more than once, which is the next mistake you tend to see once agents start returning ValueTask from hot paths to look fast.

Now build:

dotnet build Orders/Orders.csproj

It prints, trimmed to the diagnostics:

RateClient.cs(10,16): error CA1305: The behavior of 'decimal.Parse(string)' could vary based on the current user's locale settings. Replace this call in 'RateClient.GetRateAsync(string, CancellationToken)' with a call to 'decimal.Parse(string, IFormatProvider)'.
RateClient.cs(15,57): error VSTHRD002: Synchronously waiting on tasks or awaiters may cause deadlocks. Use await or JoinableTaskFactory.Run instead.
RateClient.cs(18,23): error VSTHRD100: Avoid "async void" methods, because any exceptions not handled by the method will crash the process
RateClient.cs(8,26): error CA2016: Forward the 'ct' parameter to the 'GetStringAsync' method or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token
RateClient.cs(9,9): error CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Five errors, one per defect, each with a line number and, for the analyzer rules, a link to the rule’s docs. That’s the whole point. The failure message is specific enough that the agent doesn’t have to guess what’s wrong.

The fix is short:

using System.Globalization;

namespace Orders;

public sealed class RateClient(IHttpClientFactory factory)
{
    public async Task<decimal> GetRateAsync(string id, CancellationToken ct)
    {
        var http = factory.CreateClient();
        var text = await http.GetStringAsync($"https://rates.example/{id}", ct);
        await AuditAsync(id, ct);
        return decimal.Parse(text, CultureInfo.InvariantCulture);
    }

    private static async Task AuditAsync(string id, CancellationToken ct)
    {
        await Task.Delay(10, ct);
        Console.WriteLine($"audit {id}");
    }
}

GetRateBlocking and Refresh are gone because nothing called them, which is a fair outcome for dead code the agent added “for convenience”. If something does need a sync entry point, the rule makes that a conscious decision rather than an accident.

The CA1305 choice follows the docs: a value that’s stored or read by software gets the invariant culture, and a value shown to a user gets the current culture.

Seeing the other two rules fire

The sample above doesn’t trigger CA1849 or CA2012, so here’s a second file that does:

namespace Orders;

public static class Extra
{
    public static async Task<string> ReadAsync(string path, CancellationToken ct)
    {
        Thread.Sleep(5);
        var text = File.ReadAllText(path);
        var vt = ValueTask.FromResult(text);
        var a = await vt;
        var b = await vt;
        await Task.Delay(1, ct);
        return a + b;
    }
}

The build reports:

Extra.cs(7,9): error CA1849: 'Thread.Sleep(int)' synchronously blocks. Use await instead.
Extra.cs(8,20): error CA1849: 'File.ReadAllText(string)' synchronously blocks. Await 'File.ReadAllTextAsync(string, CancellationToken)' instead.
Extra.cs(8,25): warning VSTHRD103: ReadAllText synchronously blocks. Await ReadAllTextAsync instead.
Extra.cs(9,18): error CA2012: ValueTask instances should only be consumed once, such as via an await. Consuming the same ValueTask instance multiple times can result in exceptions and data corruption.

Note that VSTHRD103 shows up as a warning and not an error, because it isn’t in the list. It overlaps with CA1849 here, so there’s no need to promote it.

Stop the agent from turning the gate off

Once the build fails, an agent has three ways out: fix the code, add #pragma warning disable, or edit .editorconfig to set the rule to none. The second and third are what a tired human does too, and an agent under instructions to “make the build pass” will take them. The rule is cheap to bypass, so the gate has to check for the bypass.

Save this as gate.sh:

#!/usr/bin/env bash
set -euo pipefail
# 1. The rules themselves must not change in an agent's diff.
if ! git diff --quiet origin/main -- .editorconfig Directory.Build.props 2>/dev/null; then
  echo "gate: .editorconfig or Directory.Build.props changed" >&2; exit 1
fi
# 2. No new suppressions in added lines.
if git diff -U0 origin/main -- '*.cs' 2>/dev/null | grep -E '^\+.*(#pragma warning disable|SuppressMessage|SuppressMessageAttribute)'; then
  echo "gate: suppression added" >&2; exit 1
fi
# 3. The build is the gate.
dotnet build Orders/Orders.csproj --nologo -v q

It compares the working tree to origin/main, so it sees uncommitted edits as well as commits. Run it against a branch where the agent has added a pragma, and it prints the offending line and exits 1:

+        #pragma warning disable CA1305
gate: suppression added

Append dotnet_diagnostic.CA2016.severity = none to .editorconfig instead, and it stops at step 1:

gate: .editorconfig or Directory.Build.props changed

With the rules untouched and the pragma gone, the build itself fails on CA1305 again (exit 1). With the fixed RateClient, it ends like this:

Build succeeded.
    0 Warning(s)
    0 Error(s)

Two limits are worth knowing. git diff ignores untracked files, so a brand-new .cs file with a pragma isn’t seen until it’s added; run git add -N . first (or run the script in CI, where the files are committed). And a legitimate suppression is sometimes right, so the script’s failure should send a human to the PR, not strand the agent. A human who agrees can edit the rules in a separate PR, where the change is the whole diff.

Give the agent the loop

The gate is the check. This is the prompt that uses it, written to work in any agent that can run a shell:

Implement the task. Before you say you're done, run ./gate.sh.
If it fails, read each diagnostic, fix the code it points at, and run it again.
You must not edit .editorconfig, Directory.Build.props or gate.sh, and you must not
add #pragma warning disable or SuppressMessage. If a rule seems wrong for a line,
stop and tell me which rule, which line and why, instead of silencing it.
Pass CancellationToken.None only where the call really must outlive the request,
and say so in a comment.

Two parts matter most. “Stop and tell me” gives the agent a legitimate exit, so the only way left to get green is to fix the code. And the CancellationToken.None line follows the CA2016 docs, which say that passing default or CancellationToken.None explicitly is the way to say “I know, and I mean it”. An agent that has to type that out has made a visible decision, and a reviewer can search the diff for it.

This part is documented behaviour and not something observed: the loop depends on your agent obeying the prompt, and the script is what catches it when it doesn’t.

Put it in CI

The same script runs unchanged on a pull request. The checkout needs the base branch available as origin/main (a full-history clone, or a fetch of main), because both diff checks compare against it. If the base branch has another name, change it in the script. In CI the rules and the pragma check guard against a human as much as an agent, which is no bad thing.

Make it yours

If the codebase is old, don’t turn everything on in one go. Promote one rule at a time, starting with CA2016 and VSTHRD100, which are cheap to fix and each prevent a production incident. Take CA1305 last, because it touches every ToString and Parse in the codebase.

Teams that already run StyleCop or Roslynator can put these rules in the same .editorconfig. The gate script doesn’t care which analyzers are installed, only that the build fails.

What goes wrong

The analyzers see syntax and types, not behaviour. CA2016 forwards the token, but it can’t tell you whether a method that takes the token actually honours it. A hand-written loop that never checks ct.IsCancellationRequested passes the build and still ignores a disconnect.

A latest-recommended analysis level moves when the SDK moves. A new SDK can add warnings, and with WarningsAsErrors on specific IDs only those become errors, so upgrades stay quiet unless one of your listed rules changes. If you promote everything with TreatWarningsAsErrors, an SDK bump can break the build with no code change. Set AnalysisLevel to a specific version, as the code analysis overview describes, if you’d rather upgrade the SDK and the rules separately.

The pragma check is a grep, and a determined agent can route around a grep, for example with a suppression written in a form the pattern doesn’t match. That is why the prompt says what to do instead and the PR review still reads the diff.

Don’t bother with this on a throwaway prototype or a console tool with no async code. It earns its keep on a service with many hands on it, human or otherwise.

First 15 minutes

Create the three files in a branch of a real service, run dotnet build, and count the errors. The number is the size of the problem. Fix the cancellation and async void ones first, commit the rules once the build is green, and add gate.sh to the prompt your team already gives its agents.