Repository navigation
Concurrency Analyzers
Ferrous.Concurrency brings Rust's data-owning Mutex<T> and AsyncMutex<T> (compiled with .NET 11 runtime-async=on) to .NET, paired with Ferrous.Concurrency.Analyzers (FE0500–FE0501) to catch data races and !Send captures at compile time.
In vanilla .NET, a Lock or SemaphoreSlim sits alongside the data it protects—nothing in the type system binds them together, so a later maintainer can easily add a read path that forgets to take the lock:
// Vanilla C#: lock and data are completely decoupled
public sealed class MetricsStore
{
private readonly Lock _gate = new();
private readonly Dictionary<string, long> _counts = new();
public void Increment(string key)
{
lock (_gate)
{
_counts[key] = _counts.GetValueOrDefault(key) + 1;
}
}
// Easy mistake: forgot `lock (_gate)` — compiles cleanly, races under load.
public long GetCount(string key) => _counts.GetValueOrDefault(key);
}With Ferrous.Concurrency, Mutex<T> owns the Dictionary<string, long>. It is syntactically impossible to touch _counts without first acquiring a stack-allocated ref struct MutexGuard<T>:
using Ferrous.Concurrency;
public sealed class MetricsStore
{
private readonly Mutex<Dictionary<string, long>> _counts = new(new());
public void Increment(string key)
{
using var guard = _counts.Lock();
guard.Value[key] = guard.Value.GetValueOrDefault(key) + 1;
}
public long GetCount(string key)
{
using var guard = _counts.Lock();
return guard.Value.GetValueOrDefault(key);
}
}- Because
MutexGuard<T>is aref struct, C# itself refuses to compile if you try to hold it across anawait(CS4007), box it, or capture it in a lambda (CS8175). - Because
Lock()andMutexGuard<T>are marked[MustUse], forgettingusing var guard = ...triggersFE0001. - When you do need to hold a lock across an
await(e.g., refreshing an OAuth token over HTTP), useAsyncMutex<T>, which has a zero-allocation uncontendedValueTaskfast path and compiles with.NET 11runtime-async=on:
private readonly AsyncMutex<AuthToken> _token = new(AuthToken.Empty);
public async ValueTask<AuthToken> GetValidTokenAsync(CancellationToken ct)
{
using var guard = await _token.LockAsync(ct);
if (guard.Value.IsExpired)
{
guard.Value = await FetchNewTokenAsync(ct);
}
return guard.Value;
}Vanilla .NET lets you capture a non-thread-safe DbContext, List<T>, or UI-bound service inside Task.Run(...) or Parallel.ForEach(...), and lets you declare static readonly Dictionary<string, Session> globals that race across concurrent requests:
// Vanilla C#: compiles with zero warnings, fails intermittently under concurrency
public static class SessionCache
{
public static readonly Dictionary<string, string> Active = new(); // Data race
}
public async Task ProcessOrdersAsync(AppDbContext db, List<Order> results)
{
await Task.Run(() => results.Add(db.Orders.First())); // Concurrent DbContext + List<T> corruption
}Ferrous.Concurrency.Analyzers brings Rust's Send boundary and static mut discipline to C#:
-
FE0500flags captures of[ThreadConfined]types and well-known thread-unsafe BCL/EF types (List<T>,Dictionary<K, V>,HashSet<T>,Queue<T>,Stack<T>,StringBuilder,DbContext) acrossTask.Run,Parallel.*,ThreadPool.QueueUserWorkItem, andnew Thread(...). -
FE0501flags non-readonlystaticfields andstatic readonlymutable collections/arrays (unless marked[ThreadStatic]or wrapped inMutex<T>/Concurrent*/Immutable*/Frozen*).
[ThreadConfined]
public sealed class UiDispatcher { }
// error/warning FE0500: cannot send thread-confined value 'dispatcher' of type 'UiDispatcher'
// across thread boundary 'Task.Run'; help: wrap it in 'Mutex<T>' / 'AsyncMutex<T>',
// use a thread-safe collection, or copy immutable data before dispatching| ID | Default | Description |
|---|---|---|
FE0500 |
Warning | Thread-confined ([ThreadConfined] / !Send or thread-unsafe collection/DbContext) captured across Task.Run, Parallel.*, ThreadPool.QueueUserWorkItem, or new Thread(...). |
FE0501 |
Warning | Unsynchronized mutable static field (non-readonly static field or static readonly mutable collection/array without [ThreadStatic]). |
FE0502 |
Warning |
SemaphoreSlim, ReaderWriterLockSlim, or Monitor lock held across an await point (clippy::await_holding_lock). |
FE0503 |
Warning | Detached Task.Run(...) called inside a method with an active TaskScope in scope (suggests scope.Spawn(...)). |
TaskScope (compiled with .NET 11 runtime-async=on on net11.0) guarantees every spawned child task either completes or is cooperatively cancelled and drained before leaving an await using block—with fail-fast sibling cancellation and support for dynamically spawned grandchildren:
using Ferrous.Concurrency;
await TaskScope.RunAsync(async scope =>
{
Task<string> user = scope.Spawn(ct => FetchUserAsync(id, ct));
Task<int> orders = scope.Spawn(ct => CountOrdersAsync(id, ct));
await scope.WaitAllAsync();
// Both tasks are guaranteed complete; if either faulted, the sibling was cancelled & drained.
});Ferrous — Rust quality-of-life primitives, source generators, and analyzers for .NET (.NET 10 / .NET 11, NativeAOT-ready, MIT License).