Async and Concurrency¶
Rule prefix: ASYNC · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
Home · Rule index · Naming cheat sheet
This chapter covers how code awaits, cancels and synchronizes concurrent work: blocking on tasks, async void, cancellation tokens, ConfigureAwait, ValueTask, asynchronous streams, locks and shared static state. The Async suffix on a method name is set by NAM-131 and the name of an event handler by NAM-146. Calling the asynchronous EF Core and ADO.NET APIs is DATA-007, and releasing resources in async code is ERR-020 and VAR-552. How a static field is declared (readonly, visibility) is VAR-513, and per-thread state is VAR-514. Tests of async code are in page 12.
Examples are application code unless a caption says library, and application code never calls ConfigureAwait (ASYNC-013). The CA rules in this chapter report in the build at warning, except CA2007, which ships as suggestion and reports only for library output. Roslyn has no diagnostic for async void (ASYNC-011), and only part of ASYNC-016 is enforced: the compiler reports a token without [EnumeratorCancellation] (CS8425) but not a missing token. ReSharper and Rider report both in the IDE. ASYNC-015 and ASYNC-021 are marked Manual: reviewers check them, and page 15 lists them in the "Manual review only" table.
Rule index¶
| ID | Level | Rule | Enforced |
|---|---|---|---|
| ASYNC-010 | DO | await every task through the whole call chain, and never block on a task with .Result, .Wait() or .GetAwaiter().GetResult(). |
CA1849 |
| ASYNC-011 | DO NOT | declare an async void method or lambda except as an event handler; return Task or Task<T> from every other async method and async lambda. |
ReSharper: AsyncVoidMethod |
| ASYNC-012 | DO | give every async method that starts cancellable work, including an interface member, a CancellationToken cancellationToken = default as its last parameter, and pass that token to every call that accepts one. |
CA1068, CA2016 |
| ASYNC-013 | DO | append .ConfigureAwait(false) to every await in reusable library code, and never call ConfigureAwait in application or test code. |
CA2007 |
| ASYNC-014 | DO | return Task or Task<T> from async methods unless a profiler measurement shows the task allocation on a hot path, and await each ValueTask or ValueTask<T> exactly once, directly at the call, without storing it. |
CA2012 |
| ASYNC-015 | DO | await the inner task when the method has a using declaration or a try block around the call, and return the task without async and await only from a method that just forwards the call, optionally after synchronous argument validation. |
Manual |
| ASYNC-016 | DO | return IAsyncEnumerable<T> from a method that produces items asynchronously one at a time, and give it a last parameter [EnumeratorCancellation] CancellationToken cancellationToken = default. |
CS8425, ReSharper: UseCancellationTokenForIAsyncEnumerable |
| ASYNC-017 | DO | observe cancellation with cancellationToken.ThrowIfCancellationRequested() instead of testing IsCancellationRequested and throwing yourself, and catch OperationCanceledException, never TaskCanceledException. |
CA2250 |
| ASYNC-020 | DO | lock only on a private readonly Lock field (System.Threading.Lock), never on this, a Type, a string or an object field. |
IDE0330, CA2002 |
| ASYNC-021 | DO | update a mutable static field only inside a lock on a Lock field or through Interlocked, and hold shared static collections in a concurrent or immutable collection type. |
Manual |
Async methods¶
These rules cover blocking, async void, cancellation tokens, ConfigureAwait, ValueTask, forwarding tasks and asynchronous streams.
ASYNC-010¶
DO await every task through the whole call chain, and never block on a task with .Result, .Wait() or .GetAwaiter().GetResult().
✅ Correct
namespace Contoso.Orders;
public sealed class OrderTotals(IOrderRepository repository)
{
public async Task<decimal> CalculateTotalAsync(int firstId, int secondId,
CancellationToken cancellationToken = default)
{
Order first = await repository.GetAsync(firstId, cancellationToken);
Order second = await repository.GetAsync(secondId, cancellationToken); // Awaited, never blocked on
return first.Total + second.Total;
}
}
❌ Incorrect — blocking on a task inside an async method
namespace Contoso.Orders;
public sealed class OrderTotals(IOrderRepository repository)
{
public async Task<decimal> CalculateTotalAsync(int firstId, int secondId,
CancellationToken cancellationToken = default)
{
Order first = await repository.GetAsync(firstId, cancellationToken);
Order second = repository.GetAsync(secondId, cancellationToken).Result; // Blocks the thread on the task
return first.Total + second.Total;
}
}
❌ Incorrect — a synchronous call that has an async counterpart
namespace Contoso.Orders;
public static class OrderFileCopier
{
public static async Task CopyAsync(string source, string target, CancellationToken cancellationToken = default)
{
string text = File.ReadAllText(source); // Synchronous call that has an async counterpart
await File.WriteAllTextAsync(target, text, cancellationToken);
}
}
Why: A blocked thread waits for work that may need that same thread. Where a synchronization context exists (UI frameworks, older ASP.NET), the continuation cannot run while .Result holds the context, so the call deadlocks. Where none exists, the thread-pool thread sits idle for the whole wait and starves other requests under load. .Wait() and .Result also wrap the original exception in an AggregateException; await rethrows it unchanged. CA1849 reports .Result and synchronous methods that have an async counterpart (File.ReadAllText) inside async methods and inside Task-returning methods that are not marked async. It does not report blocking inside a synchronous (void or value-returning) method, and with the .NET 10 SDK analyzers it does not report .GetAwaiter().GetResult(), so reviewers check those calls. Async EF Core and ADO.NET calls follow DATA-007.
Exceptions:
- A member whose signature you do not own and that has no async form, such as a static constructor, may block once at the outermost call, with a comment that names the reason.
- Reading
.Resultof a task that has already completed does not block, for example afterawait Task.WhenAll(first, second).
Scope: Calls to task-returning APIs from application and library code · Enforced: CA1849 · Sources: MS-TAP, MS-CA, MS-CONV, AV
ASYNC-011¶
DO NOT declare an async void method or lambda except as an event handler; return Task or Task<T> from every other async method and async lambda.
✅ Correct — an event handler that catches what it can expect
using System.Diagnostics.CodeAnalysis;
namespace Contoso.Orders;
public sealed class ShipmentNotifier(IOrderRepository repository)
{
public void Watch(Order order)
{
ArgumentNullException.ThrowIfNull(order);
order.Shipped += OnOrderShipped;
}
[SuppressMessage("Style", "IDE1006", Justification = "async void event handler; TAP suffix does not apply")]
private async void OnOrderShipped(object? sender, OrderShippedEventArgs e) // Event handler: async void is allowed
{
try
{
Order order = await repository.GetAsync(e.OrderId, CancellationToken.None);
Console.WriteLine(order.Total);
}
catch (OrderNotFoundException)
{
Console.WriteLine("Order not found");
}
}
}
❌ Incorrect — async void outside an event handler
namespace Contoso.Orders;
public sealed class ShipmentNotifier(IOrderRepository repository)
{
public async void NotifyAsync(Order order) // async void outside an event handler
{
ArgumentNullException.ThrowIfNull(order);
await repository.AddAsync(order, CancellationToken.None);
}
}
Why: The caller of an async void method gets no task, so it cannot await the work, cannot catch its exception and cannot tell when it finished. An exception that leaves the method is raised on the synchronization context or the thread pool and ends the process unless something handles it. An event delegate returns void, so a handler is the one place the signature forces async void; catch every exception the handler can expect inside it. A lambda passed where an API takes Action becomes async void as well; use the overload that takes Func<Task>. The handler name follows NAM-146, and the IDE1006 suppression shown above is the one NAM-131 prescribes. ReSharper and Rider report AsyncVoidMethod and AsyncVoidLambda in the IDE; no Roslyn diagnostic in the SDK does, so reviewers check this in code review.
Exceptions: An event handler may be async void; its body wraps the await in try and catch.
Scope: async methods and async lambdas · Enforced: ReSharper: AsyncVoidMethod · Config: resharper_async_void_method_highlighting, resharper_async_void_lambda_highlighting · Sources: MS-TAP, MS-ASYNCRET, RS-INSPECT, AV
ASYNC-012¶
DO give every async method that starts cancellable work, including an interface member, a CancellationToken cancellationToken = default as its last parameter, and pass that token to every call that accepts one.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderLoader(IOrderRepository repository)
{
public Task<Order> LoadAsync(int orderId, CancellationToken cancellationToken = default)
{
return repository.GetAsync(orderId, cancellationToken); // Token is last and forwarded
}
public static async Task<string> ReadAsync(string path, CancellationToken cancellationToken = default)
{
string text = await File.ReadAllTextAsync(path, cancellationToken); // Token is last and forwarded
return text;
}
}
❌ Incorrect — the token is not the last parameter, and a call does not receive it
namespace Contoso.Orders;
public sealed class OrderLoader(IOrderRepository repository)
{
public Task<Order> LoadAsync(CancellationToken cancellationToken, int orderId) // Token is not the last parameter
{
return repository.GetAsync(orderId, cancellationToken);
}
public static async Task<string> ReadAsync(string path, CancellationToken cancellationToken = default)
{
string text = await File.ReadAllTextAsync(path); // Token not forwarded
return text;
}
}
❌ Incorrect — the token has no default value
namespace Contoso.Orders;
public sealed class OrderLoader(IOrderRepository repository)
{
public Task<Order> LoadAsync(int orderId, CancellationToken cancellationToken) // Token has no default value
{
return repository.GetAsync(orderId, cancellationToken);
}
}
Why: The token is the only way to stop work the caller no longer wants. Last position is the .NET convention, so call sites read ReadAsync(path, cancellationToken). With = default, a caller that has no token can leave the argument out, which passes CancellationToken.None, so no overload pair is needed. A method that takes a token and does not pass it to a callee that accepts one cannot be cancelled below that call. CA1068 reports a token that is not last, and CA2016 reports a call that omits the token. An ASP.NET Core action declares a CancellationToken parameter, and model binding fills it with the request-aborted token. Async data access follows DATA-007. No analyzer reports a missing = default, so reviewers check it.
Exceptions:
- A method that starts no cancellable work (it awaits no API that takes a token and runs no long loop) takes no token.
- An override or an interface implementation keeps the parameter list of the member it overrides or implements, including its
= default; an explicit interface implementation leaves the default out, because the compiler reportsCS1066for it. - A synchronous method that observes a token takes it as a required parameter.
- Pass
CancellationToken.None, or leave the argument out, only where no token exists, such as aMainentry point or an event handler (ASYNC-011); never where a token is in scope.
Scope: Async methods that start cancellable work, including interface members and ASP.NET Core actions · Enforced: CA1068, CA2016; the default value: review · Sources: MS-TAP, MS-CA, MS-CONV, AV
ASYNC-013¶
DO append .ConfigureAwait(false) to every await in reusable library code, and never call ConfigureAwait in application or test code.
✅ Correct — library code
namespace Contoso.Orders;
public sealed class OrderArchive(IOrderRepository repository)
{
public async Task ArchiveAsync(Order order, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(order);
await repository.AddAsync(order, cancellationToken).ConfigureAwait(false); // Library: ConfigureAwait(false)
}
}
✅ Correct — application code
namespace Contoso.Orders;
public sealed class OrderSubmission(IOrderRepository repository)
{
public async Task SubmitAsync(Order order, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(order);
await repository.AddAsync(order, cancellationToken); // Application: no ConfigureAwait
}
}
❌ Incorrect — a library await without ConfigureAwait(false)
namespace Contoso.Orders;
public sealed class OrderArchive(IOrderRepository repository)
{
public async Task ArchiveAsync(Order order, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(order);
await repository.AddAsync(order, cancellationToken); // Library await without ConfigureAwait(false)
}
}
Why: A library cannot know whether its caller has a synchronization context. ConfigureAwait(false) removes the library's dependency on it, so a caller that blocks on the library's task does not deadlock. Application code owns the context: ASP.NET Core has none, and a UI application needs its context after an await, so the call changes nothing there and can break UI access. The xUnit analyzers also report it in test methods. CA2007 reports a missing call; it ships at suggestion and only for library output (dotnet_code_quality.CA2007.output_kind = DynamicallyLinkedLibrary), so application and test projects are not flooded, and the test-file section of the shipped .editorconfig sets it to none. A library team raises it with dotnet_diagnostic.CA2007.severity = warning in the library's own .editorconfig. Calling ConfigureAwait(false) on every await, including application and test code, and never calling it are the two blanket alternatives; the Roslyn .editorconfig and Google's style guide prescribe neither.
Exceptions:
- Library code that must resume on the caller's context, for example a method that updates a UI control after an
await, omits the call on thatawait. - Application code compiled as a class library stays free of the call; leave
CA2007atsuggestionthere.
Scope: await expressions; library code versus application and test code · Enforced: CA2007 · Config: dotnet_code_quality.CA2007.output_kind · Sources: MS-CONV, MS-CA, RT-GC
ASYNC-014¶
DO return Task or Task<T> from async methods unless a profiler measurement shows the task allocation on a hot path, and await each ValueTask or ValueTask<T> exactly once, directly at the call, without storing it.
✅ Correct
public static async Task<int> ReadTwiceAsync(Func<ValueTask<int>> readStock)
{
ArgumentNullException.ThrowIfNull(readStock);
int first = await readStock(); // Each ValueTask is awaited once, at the call
int second = await readStock();
return first + second;
}
❌ Incorrect — a ValueTask stored and awaited twice
public static async Task<int> ReadTwiceAsync(Func<ValueTask<int>> readStock)
{
ArgumentNullException.ThrowIfNull(readStock);
ValueTask<int> pending = readStock(); // ValueTask stored and awaited twice
int first = await pending;
int second = await pending; // Second await on the same ValueTask
return first + second;
}
Why: A Task can be awaited any number of times. A ValueTask may wrap a pooled object that returns to its pool when the first await completes, so a second await, a concurrent await or a blocking read before completion reads reused state. It saves an allocation only when a method often completes synchronously, so use it where a profiler or benchmark shows that allocation on a hot path. CA2012 reports a stored ValueTask.
Exceptions: To await a ValueTask twice, or to pass it to Task.WhenAll, call AsTask() once and use the resulting Task.
Scope: Return types of async methods and consumption of ValueTask · Enforced: CA2012 · Sources: MS-TAP, MS-CA, MS-ASYNCRET
ASYNC-015¶
DO await the inner task when the method has a using declaration or a try block around the call, and return the task without async and await only from a method that just forwards the call, optionally after synchronous argument validation.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderLookup(IOrderRepository repository)
{
public Task<Order?> FindAsync(int orderId, CancellationToken cancellationToken = default)
{
return repository.FindAsync(orderId, cancellationToken); // Whole body is the forwarding call
}
public Task<Order> GetCheckedAsync(int orderId, CancellationToken cancellationToken = default)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(orderId); // Usage error throws synchronously
return repository.GetAsync(orderId, cancellationToken); // Then the task is forwarded
}
}
❌ Incorrect — the task is returned while a using scope ends
namespace Contoso.Orders;
public sealed class OrderLookup(IOrderRepository repository)
{
public Task<Order> GetWithTimeoutAsync(int orderId, CancellationToken cancellationToken = default)
{
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
return repository.GetAsync(orderId, timeout.Token); // Returned without await: the using disposes the source first
}
}
Why: Without await, the method returns the callee's task at once. A using scope ends and a try, catch or finally block is left while the callee still runs. In the incorrect example the source is disposed before GetAsync completes, so the timeout never applies. Change that method to async and return await. A method that just forwards the call has none of these scopes, and skipping the state machine saves an allocation. Argument validation does not need an await: the Task-based Asynchronous Pattern asks a method to throw a usage error synchronously, and a non-async method does exactly that, while the same check inside an async method delivers the exception through the returned task. The differences from awaiting are small: when an exception surfaces and the stack trace, which has no state-machine frame. No analyzer in the SDK checks this convention, so reviewers do.
Scope: Methods that return the task of a single inner call · Enforced: Manual · Sources: MS-TAP, MS-ASYNCRET
ASYNC-016¶
DO return IAsyncEnumerable<T> from a method that produces items asynchronously one at a time, and give it a last parameter [EnumeratorCancellation] CancellationToken cancellationToken = default.
✅ Correct
using System.Runtime.CompilerServices;
namespace Contoso.Orders;
public sealed class OrderFeed(IOrderRepository repository)
{
public async IAsyncEnumerable<Order> StreamAsync(
IReadOnlyList<int> orderIds,
[EnumeratorCancellation] CancellationToken cancellationToken = default) // Token marked for WithCancellation
{
ArgumentNullException.ThrowIfNull(orderIds);
foreach (int orderId in orderIds)
{
Order order = await repository.GetAsync(orderId, cancellationToken);
yield return order; // Each order is yielded as soon as it arrives
}
}
}
❌ Incorrect — a token parameter without [EnumeratorCancellation]
namespace Contoso.Orders;
public sealed class OrderFeed(IOrderRepository repository)
{
public async IAsyncEnumerable<Order> StreamAsync( // Token without [EnumeratorCancellation]
IReadOnlyList<int> orderIds,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(orderIds);
foreach (int orderId in orderIds)
{
Order order = await repository.GetAsync(orderId, cancellationToken);
yield return order;
}
}
}
❌ Incorrect — an async stream without a cancellation token
namespace Contoso.Orders;
public sealed class OrderFeed(IOrderRepository repository)
{
public async IAsyncEnumerable<Order> StreamAsync(IReadOnlyList<int> orderIds) // No cancellation token
{
ArgumentNullException.ThrowIfNull(orderIds);
foreach (int orderId in orderIds)
{
Order order = await repository.GetAsync(orderId, CancellationToken.None);
yield return order;
}
}
}
Why: A consumer cancels an async stream with await foreach (...).WithCancellation(token). The compiler hands that token to the iterator only through a parameter marked [EnumeratorCancellation]; without it, the stream ignores the consumer's token and runs to the end. The default value = default lets callers that do not cancel omit the argument, and the token stays last as in ASYNC-012. Roslyn reports CS8425 for a token parameter without the attribute (the first incorrect example) and CS8424 for the attribute on a member where it has no effect, but not for a missing token. A method with no token at all (the second incorrect example) is reported by ReSharper and Rider as UseCancellationTokenForIAsyncEnumerable in the IDE, and reviewers check it in code review.
Exceptions:
- Put the attribute on the iterator method itself. On an interface or abstract member it has no effect, and the implementing iterator declares it.
- A guard inside an async iterator, such as
ThrowIfNull(orderIds)above, runs at the firstMoveNextAsync, not at the call. To validate at the call, make the public method a non-iterator that validates and returns a privateasync IAsyncEnumerable<T>iterator; the private iterator then carries[EnumeratorCancellation], and the public method passes its token on.
Scope: Methods that produce a sequence asynchronously · Enforced: CS8425, ReSharper: UseCancellationTokenForIAsyncEnumerable · Config: resharper_use_cancellation_token_for_i_async_enumerable_highlighting · Sources: MS-TAP, RS-INSPECT
ASYNC-017¶
DO observe cancellation with cancellationToken.ThrowIfCancellationRequested() instead of testing IsCancellationRequested and throwing yourself, and catch OperationCanceledException, never TaskCanceledException.
✅ Correct — observe the token
public static int CountLines(IReadOnlyList<Order> orders, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(orders);
int count = 0;
foreach (Order order in orders)
{
cancellationToken.ThrowIfCancellationRequested(); // Throws OperationCanceledException
count += order.Lines.Count;
}
return count;
}
✅ Correct — catch the base type
public static async Task<bool> TryRunAsync(Func<CancellationToken, Task> work,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(work);
try
{
await work(cancellationToken);
return true;
}
catch (OperationCanceledException)
{
return false; // Also catches TaskCanceledException, which derives from it
}
}
❌ Incorrect — a hand-written cancellation check
public static int CountLines(IReadOnlyList<Order> orders, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(orders);
int count = 0;
foreach (Order order in orders)
{
if (cancellationToken.IsCancellationRequested) // Hand-written cancellation check
{
throw new OperationCanceledException();
}
count += order.Lines.Count;
}
return count;
}
❌ Incorrect — a handler for TaskCanceledException
public static async Task<bool> TryRunAsync(Func<CancellationToken, Task> work,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(work);
try
{
await work(cancellationToken);
return true;
}
catch (TaskCanceledException) // Misses cancellations thrown as OperationCanceledException
{
return false;
}
}
Why: ThrowIfCancellationRequested throws an OperationCanceledException that carries the token, so callers and Task.Run can tell which token cancelled. The hand-written form needs four lines for the same effect and drops the token when the constructor argument is forgotten. TaskCanceledException derives from OperationCanceledException, and ThrowIfCancellationRequested throws the base type, so catch (TaskCanceledException) misses those cancellations; reviewers check the catch clause. CA2250 reports the hand-written check.
Exceptions: An IsCancellationRequested test that does something other than throw, such as returning a partial result or leaving a loop to flush a buffer, is not covered.
Scope: Cancellation checks and handlers of cancelled operations · Enforced: CA2250 · Sources: MS-TAP, MS-CA
Locks and shared state¶
These rules cover the lock type and the update of static state that several threads share.
ASYNC-020¶
DO lock only on a private readonly Lock field (System.Threading.Lock), never on this, a Type, a string or an object field.
C# 13: The
Locktype needs .NET 9 and C# 13. On an older target framework or aLangVersionbelow 13, lock on aprivate readonly objectfield;IDE0330does not report there.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderNumberSequence
{
private readonly Lock _gate = new(); // Lock type, not object
private int _next;
public int GetNextNumber()
{
lock (_gate)
{
_next++;
return _next;
}
}
}
❌ Incorrect — an object used as a lock, and a lock on this
namespace Contoso.Orders;
public sealed class OrderNumberSequence
{
private readonly object _gate = new(); // object used as a lock
private int _next;
public int GetNextNumber()
{
lock (_gate)
{
_next++;
return _next;
}
}
public void Reset()
{
lock (this) // locks on this
{
_next = 0;
}
}
}
Why: System.Threading.Lock is a dedicated lock type: the lock statement on it uses Lock.EnterScope instead of Monitor, and the field's type states its purpose. Any code that can reach this, a Type object or a string can take the same lock, so unrelated code can block yours or deadlock with it; string literals with the same text are one interned object. A private field cannot be reached from outside. IDE0330 reports an object field used as a lock, and CA2002 reports a lock on this, on a Type object (lock (typeof(Order))) or on a string.
Exceptions: A lock cannot contain await. To hold exclusive access across an await, use a SemaphoreSlim created with an initial count of 1 and call WaitAsync.
Scope: Objects used with the lock statement · Enforced: IDE0330, CA2002 · Config: csharp_prefer_system_threading_lock · Sources: MS-IDE, MS-LANG-13
ASYNC-021¶
DO update a mutable static field only inside a lock on a Lock field or through Interlocked, and hold shared static collections in a concurrent or immutable collection type.
✅ Correct — an atomic update
private static int _placed;
public static int Placed => Volatile.Read(ref _placed);
public static int RecordPlaced() => Interlocked.Increment(ref _placed); // Atomic read-modify-write
✅ Correct — a concurrent collection
using System.Collections.Concurrent;
namespace Contoso.Orders;
public static class OrderCache
{
private static readonly ConcurrentDictionary<int, Order> OrdersById = new();
public static Order GetOrAdd(Order order)
{
ArgumentNullException.ThrowIfNull(order);
return OrdersById.GetOrAdd(order.Id, order);
}
}
❌ Incorrect — unsynchronized updates of shared static state
private static int _placed;
private static readonly Dictionary<int, Order> OrdersById = [];
public static int Placed => Volatile.Read(ref _placed);
public static void RecordPlaced() => _placed++; // Unsynchronized read-modify-write on shared state
public static void Add(Order order) => OrdersById[order.Id] = order; // Plain Dictionary written from many threads
Why: _placed++ is a read, an addition and a write. Two threads can read the same value, and one increment is lost. Interlocked makes the update one atomic operation, and Volatile.Read returns the latest written value. A Dictionary<TKey, TValue> that one thread writes while another reads has undefined behaviour. A ConcurrentDictionary<TKey, TValue> or an immutable collection needs no lock from the caller. Visibility and readonly of the field are VAR-513; CA2211 covers visibility and not thread safety, so no analyzer checks this rule.
Exceptions:
- A static field assigned once in its initializer or static constructor and never changed is
readonlyand needs no lock (VAR-513). - Per-thread state belongs in
ThreadLocal<T>orAsyncLocal<T>(VAR-514).
Scope: Mutable static fields and static collections · Enforced: Manual · Sources: MS-CA, RT-STYLE
Related¶
- NAM-131 and NAM-146: the
Asyncsuffix and the name of an event handler. - DATA-007: asynchronous EF Core and ADO.NET calls with the method's token.
- ERR-020 and VAR-552: disposing resources, including
await using. - VAR-513 and VAR-514: static fields and per-thread state.
- TEST-011: test method names end in
_Test, never inAsync, even when the test isasync.
Sources¶
AV · MS-CA · MS-CONV · MS-IDE · MS-LANG-13 · MS-ASYNCRET · MS-TAP · RS-INSPECT · RT-GC · RT-STYLE
Previous: Exceptions and Error Handling · Home · Next: Testing Conventions