Skip to content

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 every await of a Task or ValueTask in library, API client and service code outside grains and UI components.
  • Use await using and await foreach with .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

var order = await this.repository.GetByIdAsync(orderId, token).ConfigureAwait(false);

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.cs files and test projects (ENF-027).
  • The template .editorconfig that 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 or GrainFactory throws an "activation access violation".
  • Blazor components. After ConfigureAwait(false) the continuation leaves the renderer's context, so updating component state or calling StateHasChanged can fail or race with rendering.

Do

  • In grain methods, await without ConfigureAwait: await this.state.WriteStateAsync();.
  • In .razor and .razor.cs files, await without ConfigureAwait.
  • 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 an await inside a grain or a component.
  • Work around a lost context with InvokeAsync(StateHasChanged) after ConfigureAwait(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.cs files in the change for ConfigureAwait(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 await the 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() or GetAwaiter().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( and GetAwaiter().GetResult() outside tests.
  • VSTHRD002 reports them once the .editorconfig is 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 Task from asynchronous methods.
  • Use async void only for a handler of a .NET event, and catch every exception inside it.
  • In Blazor, prefer EventCallback and Func<Task> callbacks, which return a task.

Don't

  • Write an async void helper, 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 CancellationToken parameter, last in the list. In application code it may default to default.
  • Pass the token to every asynchronous call that accepts one.

Don't

  • Pass CancellationToken.None or default when 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 Task or ValueTask, takes a CancellationToken as its last parameter. CA2016 does not check this.
  • Search the change for CancellationToken.None outside tests and start-up code. Also search for default or default(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.Run to give it an asynchronous signature.
  • Use Task.Run in 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.