Async and concurrency standard¶
This page sets the rules for asynchronous and concurrent C# code in ConnectSoft repositories and generated services. It is written for engineers who write or review code that awaits. Most rules depend on where the code runs, so the page starts with the code families.
The naming of asynchronous methods is covered by CS-NAM-005.
Code families¶
Where code runs decides how its continuations must be scheduled:
| Family | Examples | Continuation after await |
|---|---|---|
| Library and API client | ConnectSoft.Extensions.*, typed HTTP clients |
Must not assume any context, because the caller may have one. |
| Service code | Domain services, repositories, controllers, consumers, jobs | Runs on the thread pool; no context to return to. |
| Orleans grain | Classes deriving from Grain or implementing IGrainBase |
Must return to the grain's activation scheduler. |
| Blazor UI | .razor and .razor.cs components |
Must return to the renderer's synchronization context. |
| Tests | Unit, acceptance and end-to-end tests | No requirement. |
ADR-0103 section 4 records the grain and UI exceptions.
Rules¶
CS-ASY-001: Use ConfigureAwait(false) in library, API client and service code¶
Severity: major · Applies to: library, api-client, service · Enforced by: analyzer CA2007 (target: ENF-027) · Status: active
Why¶
A library awaited from code that has a synchronization context, such as a UI or a legacy host, deadlocks or runs slowly when its continuations try to return to that context. ConfigureAwait(false) removes the dependency. In service code it costs nothing and keeps code safe to move into a library. More than 90% of awaits in ConnectSoft service and library code already use it.
Do¶
- Add
.ConfigureAwait(false)to everyawaitof aTaskorValueTaskin library, API client and service code outside grains and UI components. - Use
await usingandawait foreachwith.ConfigureAwait(false)on the disposable or the enumerable.
Don't¶
- Add it in Orleans grains or Blazor components (CS-ASY-002).
- Require it in tests. It is allowed there but not needed.
Example¶
How to check¶
- CA2007 reports a missing call. Turn it on as a warning for library, API client and service code, and off for grain files,
*.razor.csfiles and test projects (ENF-027). - The template
.editorconfigthat should configure CA2007 is broken today (ENF-001), so check by hand.
CS-ASY-002: Never use ConfigureAwait(false) in Orleans grains or Blazor components¶
Severity: blocker · Applies to: service, blazor, template · Enforced by: manual (target: ENF-027) · Status: active
Why¶
- Grains. Orleans runs each grain activation on a single-threaded scheduler. After
ConfigureAwait(false)the continuation runs on a thread-pool thread, and the next call to grain state, reminders, timers orGrainFactorythrows an "activation access violation". - Blazor components. After
ConfigureAwait(false)the continuation leaves the renderer's context, so updating component state or callingStateHasChangedcan fail or race with rendering.
Do¶
- In grain methods, await without
ConfigureAwait:await this.state.WriteStateAsync();. - In
.razorand.razor.csfiles, await withoutConfigureAwait. - Keep
ConfigureAwait(false)in the services that grains and components call. Only the grain's or component's own awaits must omit it. - When CA2007, MA0004 or VSTHRD111 is enabled, turn it off for grain and component files with a reason, as ADR-0103 section 4 requires, for example with a class-level pragma in a grain.
- In a component, wrap work that arrives from another thread, such as a timer or an event raised by a singleton, in
InvokeAsync.
Don't¶
- Add
ConfigureAwait(false)to anawaitinside a grain or a component. - Work around a lost context with
InvokeAsync(StateHasChanged)afterConfigureAwait(false)in new component code.
Example¶
// Grain
#pragma warning disable CA2007 // Grain code must resume on the activation scheduler (ADR-0103 section 4).
public async Task Withdraw(decimal amount)
{
this.state.State.Balance -= amount;
await this.state.WriteStateAsync();
}
#pragma warning restore CA2007
// Blazor component code-behind
protected override async Task OnInitializedAsync()
{
this.orders = await this.OrdersClient.GetOrdersAsync(this.cancellation.Token);
}
How to check¶
- Search grain files (
: Grain,IGrainBase) and*.razor,*.razor.csfiles in the change forConfigureAwait(false). The count added must be 0. - Existing component and grain code that breaks this rule is listed under ENF-025, ENF-026 and ENF-042; only new code is flagged.
- In new component code, timer callbacks and handlers of events raised by a singleton run their work inside
InvokeAsync.
CS-ASY-003: Do not block on asynchronous code¶
Severity: blocker · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer VSTHRD002 (target: ENF-001) · Status: active
Why¶
.Result, .Wait() and GetAwaiter().GetResult() hold a thread while the task runs. Under load this starves the thread pool. On a single-threaded scheduler it deadlocks: when a grain awaits code that blocks, the blocked call occupies the activation while the continuation it waits for is queued behind it, and the call fails only when the Orleans request timeout expires.
Do¶
- Make the calling method asynchronous and
awaitthe task, up to the entry point. - When a grain must call code that blocks internally and cannot be changed yet, move that call off the activation at the grain boundary:
await Task.Run(() => processor.ExpireOrder(orderId));.
Don't¶
- Call
.Result,.Wait()orGetAwaiter().GetResult()in production code. - Fix sync-over-async at every call site inside a shared service when the problem is one grain boundary.
Example¶
// Do
var connection = await factory.CreateConnectionAsync(token).ConfigureAwait(false);
// Don't
var connection = factory.CreateConnectionAsync(token).GetAwaiter().GetResult();
How to check¶
- Search the change for
.Result,.Wait(andGetAwaiter().GetResult()outside tests. - VSTHRD002 reports them once the
.editorconfigis repaired (ENF-001). Existing blocking calls are listed under ENF-030.
CS-ASY-004: Use async void only for event handlers¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer VSTHRD100 (target: ENF-001) · Status: active
Why¶
An exception thrown from an async void method cannot be caught by the caller and crashes the process or the Blazor circuit. The caller also cannot wait for it to finish.
Do¶
- Return
Taskfrom asynchronous methods. - Use
async voidonly for a handler of a .NET event, and catch every exception inside it. - In Blazor, prefer
EventCallbackandFunc<Task>callbacks, which return a task.
Don't¶
- Write an
async voidhelper, callback or lifecycle method.
Example¶
private async void OnAuthenticationStateChanged(Task<AuthenticationState> task)
{
try
{
await this.RefreshAsync(task);
}
catch (Exception ex)
{
this.logger.Here(log => log.LogError(exception: ex, message: "Failed to refresh after an authentication change"));
}
}
How to check¶
Search the change for async void. Each hit is an event handler whose body is wrapped in try/catch.
CS-ASY-005: Accept a CancellationToken and pass it on¶
Severity: major · Applies to: service, library, api-client, template · Enforced by: analyzer CA2016 · Status: active
Why¶
A cancelled HTTP request or a stopping host should stop its database queries and outgoing calls. That works only when every asynchronous method in the chain receives the token and passes it on.
Do¶
- Give every public asynchronous method a
CancellationTokenparameter, last in the list. In application code it may default todefault. - Pass the token to every asynchronous call that accepts one.
Don't¶
- Pass
CancellationToken.Noneordefaultwhen a token is in scope. - Drop the token at a layer boundary, for example between a controller and a domain service.
Example¶
public async Task<IOrder> GetOrder(GetOrderInput input, CancellationToken token = default)
{
return await this.repository.GetByIdAsync(input.OrderId, token).ConfigureAwait(false);
}
How to check¶
- CA2016 reports a token that is not forwarded.
- Every new public asynchronous method, such as one that returns
TaskorValueTask, takes aCancellationTokenas its last parameter. CA2016 does not check this. - Search the change for
CancellationToken.Noneoutside tests and start-up code. Also search fordefaultordefault(CancellationToken)passed as the token where a token is in scope.
CS-ASY-006: Use Task.Run only to offload work, never to fake asynchrony¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
In a service, Task.Run around synchronous code only moves the work to another thread-pool thread and adds a context switch. A library that wraps synchronous work in Task.Run hides its real cost from the caller.
Do¶
Use Task.Run only to:
- move CPU-bound work off a UI thread;
- leave a grain's activation scheduler for code that must not run on it (CS-ASY-003).
Don't¶
- Wrap a synchronous method in
Task.Runto give it an asynchronous signature. - Use
Task.Runin request handling code to run work "in the background". Use a hosted service or a job instead.
How to check¶
Each new Task.Run in the change has one of the reasons above in the code or in a comment.
CS-ASY-007: Return per-call results instead of reading shared state after an await¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
When a method leaves part of its result on a shared field, for example a total count on a client, two overlapping calls overwrite each other. The caller reads the field after its own await and gets the value of whichever call finished last. The result looks plausible, so the defect is hard to see.
Do¶
- Return everything a call produces as its result, for example a
(Rows, Total)tuple or a page object. - Treat any field written by an asynchronous method as shared between all its callers.
Don't¶
- Store a per-call result on a field of a shared service, client or component and read it after the
await.
Example¶
// Do
OrderPage page = await this.client.SearchOrdersAsync(filter, token).ConfigureAwait(false);
// Don't
var rows = await this.client.SearchOrdersAsync(filter, token).ConfigureAwait(false);
var total = this.client.LastSearchTotal;
How to check¶
Look for fields or properties that an asynchronous method sets and a caller reads after awaiting it.