Compze.Threading 0.13.0-alpha

This is a prerelease version of Compze.Threading.
dotnet add package Compze.Threading --version 0.13.0-alpha
                    
NuGet\Install-Package Compze.Threading -Version 0.13.0-alpha
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Compze.Threading" Version="0.13.0-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Compze.Threading" Version="0.13.0-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Compze.Threading" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Compze.Threading --version 0.13.0-alpha
                    
#r "nuget: Compze.Threading, 0.13.0-alpha"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Compze.Threading@0.13.0-alpha
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Compze.Threading&version=0.13.0-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Compze.Threading&version=0.13.0-alpha&prerelease
                    
Install as a Cake Tool

Compze.Threading

Pit of success threading primitives. Impossible to forget to lock. Automatically resolves and diagnoses deadlocks, including both the involved stack traces in the exception.

The Problem

With the tools built into the BCL:

  • Nothing stops you from accessing shared state without locking.
  • Forget once and you have an intermittent bug apt to be very hard to diagnose.
  • Deadlocks hang forever bringing production software to a permanent halt.

Usage requires constant vigilance. Getting it disastrously wrong is all too easy.

Our Solutions

Automatic Deadlock Resolution with Dual Stack Traces

Every lock acquisition in all the abstractions shown below use a LockTimeout internally when acquiring locks (default 2 minutes). When deadlocks occur the timeout elapses and we capture both stack traces in the exception thrown: the thread that was blocked and the thread that was blocking it. No more guessing which thread held the lock.

💡 If the "winning" thread does not promptly (within 10 seconds) release the lock after the deadlock is resolved its stacktrace will not occur in the exception.

💡 The timeout covers taking a lock. A wait for a condition waits forever by default (WaitTimeout.Default is WaitTimeout.Infinite), since nothing says how long a wait may take in general: a worker waiting for work may rightly wait for hours. Pass a WaitTimeout, to the call or when creating the monitor, where a condition that never comes true should fail instead.

IThreadShared<T> Make Forgetting to Lock Impossible.

class MyThreadSafeClass
{
    readonly IThreadShared<PrivateImplementation> _inner = IThreadShared.New(new PrivateImplementation());

    void Add(string key, int value) => _inner.Locked(it => it.Add(key, value));
    int Get(string key) => _inner.Locked(it => it.Get(key));

    class PrivateImplementation{/**/}
}

💡 Note: There is no way to access the PrivateImplementation instance without acquiring the lock. This resolves whole categories of bugs in one fell swoop.

IAwaitableThreadShared<T> — Condition Waits with Read/Update Semantics

To be able to efficiently wait for shared state to reach a certain condition you need IAwaitableThreadShared instead:

class WorkTracker
{
    readonly IAwaitableThreadShared<PrivateImplementation> _inner = IAwaitableThreadShared.New(new PrivateImplementation());

    void Add(WorkItem item) => _inner.Update(it => it.Add(item));

    void Dispose()
    {
        _inner.UpdateWhen(it => it.IsEmpty, it => it.Dispose());
    }

    class PrivateImplementation{/**/}
}

💡 Read declares that the code changes nothing, and Update that it changes the state. That tells whoever reads the code which is which, and it lets a read skip waking the waiting conditions: only an update can make a condition true. So a change inside Read is forbidden: it wakes no waiting condition, which goes on waiting. Conditions must not change the state either.

💡 All locks are exclusive, read locks included. Read declares what the code does, not that it may run alongside other reads.

API Overview

Simple Locking — IThreadShared<T>

class MyService
{
    readonly IThreadShared<MyState> _state = IThreadShared.New(new MyState());

    public int GetValue() => _state.Locked(state => state.Value);
    public void SetValue(int value) => _state.Locked(state => state.Value = value);
}

One operation: Locked. The shared state is the lambda parameter. No way to misuse it.

Read/Update/Wait — IAwaitableThreadShared<T>

class WorkTracker
{
    readonly IAwaitableThreadShared<MyState> _state = IAwaitableThreadShared.New(new MyState());
    // or: IAwaitableThreadShared.New(new MyState(), LockTimeout.Seconds(5), WaitTimeout.Seconds(30));

    // Read under lock. Does NOT wake waiting threads.
    public int GetValue() => _state.Read(state => state.Value);

    // Update under lock and notify all waiting threads to re-evaluate their conditions
    public void SetValue(int value) => _state.Update(state => state.Value = value);  
    

    // Wait for condition to become true, then read while still holding the lock used for checking the condition
    public int AwaitReady() => _state.ReadWhen(state => state.IsReady, state => state.Value);

    // Wait for condition to become true, then update while still holding the lock used for checking the condition, then notify all waiting threads about the update before releasing the lock.
    public void ProcessWhenReady() => _state.UpdateWhen(state => state.HasWork, state => state.Process()); 

    // Wait for condition to become true
    public void AwaitDone() => _state.Await(state => state.IsDone);

    // Each waiting method has an async counterpart that holds no thread while it waits: see "Async condition waits" below
    public async Task AwaitDoneAsync() => await _state.AwaitAsync(state => state.IsDone);
}

Lower-Level — IMonitor and IAwaitableMonitor

CRITICAL: The *When methods (TakeReadLockWhen, TakeUpdateLockWhen, ReadWhen, UpdateWhen, Await, etc.) release the lock while waiting for a condition, just like Monitor.Wait. When the condition is met, the lock is reacquired before the method returns. This means that if you hold the lock and call a waiting method, other threads can acquire the lock during the wait. All IAwaitableCriticalSection implementations — including IAwaitableMonitor and IAwaitableMutex — share this behavior.

Async condition waits hold no thread while they wait

TryAwaitAsync, ReadWhenAsync, UpdateWhenAsync and TryUpdateWhenAsync are the condition waits for async code. While the condition is false nothing waits but a task, which the next update-lock release completes, so no thread is parked: a synchronous wait on a thread-pool thread holds that thread for as long as it waits, and enough of them starve the pool.

public async Task<AType> AwaitValueAsync() => await _monitor.ReadWhenAsync(() => _aField != null, () => _aField);

Taking the lock is still synchronous, and brief: it waits only while another holder is inside a critical section. The condition and the function a wait runs once the condition holds run under the lock, so they are synchronous. And unlike the synchronous waits, an async wait can't release a lock its caller already holds, because it may resume on another thread: starting one while holding the lock fails at once.

Wrap all logic in existing public methods inside calls to _monitor to quickly migrate existing classes:
class MyThreadSafe
{
    IMonitor _monitor = IMonitor.New();
    
    public void DoStuff() => _monitor.Locked(() => 
    {
        //implementation here
    });
}

class MyAwaitableThreadSafe
{
    IAwaitableMonitor _monitor = IAwaitableMonitor.New();

    public AType ReadAType() => _monitor.Read(() => _aField);
    public void UpdateSomething(AType value) => _monitor.Update(() => _aField = value);
    public AType AwaitValue() => _monitor.ReadWhen(() => _aField != null, () => _aField);

}
Lock the entire method body with a using statement. For very hot path code, where even a lambda allocation might be worth caring about.
class MyThreadSafe
{
    IMonitor _monitor = IMonitor.New();
    
    public void DoStuff()
    {
        using var heldLock = _monitor.TakeLock();
        //implementation here
    }
}

class MyAwaitableThreadSafe
{
    IAwaitableMonitor _monitor = IAwaitableMonitor.New();

    public AType ReadAType()
    {
        using var readLock = _monitor.TakeReadLock();
        return _aField;
    }

    public void UpdateSomething(AType value)
    {
        using var updateLock = _monitor.TakeUpdateLock();
        _aField = value;
    }
    public AType AwaitValue()
    {
        using var readLock = _monitor.TakeReadLockWhen(() => _aField != null);
        return _aField;
    }
}

💡 Take*Lock operations are zero allocation, the disposables returned are reused

Lock only in chosen sections of code: Advanced/rare/risky usage:
class RiskyExample
{
    readonly IAwaitableMonitor _monitor = IAwaitableMonitor.WithDefaultTimeout();

    public void ReadSomething()
    {
        //Unsynchronized code
        using(_monitor.TakeReadLock()) { /* read */ }
        //Unsynchronized code
    }

    public void UpdateSomething()
    {
        //Unsynchronized code
        using(_monitor.TakeUpdateLock()) { /* update, notifies waiters */ }
        //Unsynchronized code
    }

    public void WaitThenRead()
    {
        //Unsynchronized code
        using(_monitor.TakeReadLockWhen(() => ready)) { /* waits for condition, then reads */ }
        //Unsynchronized code
    }
}

💡 WARNING: Think carefully before doing this. Much of the problems with BCL primitives come right back. Profile before you assume that more granular locking is needed for performance. It is far more rare than you may think.

Lazy Initialization — LazyCE<TValue>

A value that its factory creates the first time it is read, like Lazy<T> in its default thread-safety mode: the factory runs once, however many threads read the value for the first time at the same moment, and the others wait for it and get the value it created. It differs from Lazy<T> where Lazy<T> gets in the way:

  • A factory that throws runs again on the next read, instead of its exception being cached for good.
  • A deadlock between factories throws a TimeoutException after LockTimeout.Default, instead of hanging.
  • A factory that reads the value it is creating throws an InvalidOperationException, as Lazy<T> does.
  • A null value is a value: a factory that creates null runs once, as for any other value, and IsInitialized tells a value created null from one not yet created.
  • An instance is one 32-byte object, cheap enough to create by the million: it allocates no lock, but locks on itself, and only while the value is being created. So don't lock on an instance from outside: that code would share its lock.
  • It lets go of its factory once the value is created, so the factory, and whatever it captured, can be collected.
public class Settings
{
    readonly LazyCE<IConfigurationSection> _section = new(() => LoadTheSection());

    public IConfigurationSection Section => _section.Value;
}
Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (22)

Showing the top 5 NuGet packages that depend on Compze.Threading:

Package Downloads
Compze.Internals.SystemCE

For Compze internal use only. Do not take a direct dependency on this package.

Compze.DependencyInjection

Package Description

Compze.Tessaging

Messaging infrastructure for the Compze framework including command, query, and event handling.

Compze.Abstractions

Core abstractions for the Compze framework: entity IDs, message type contracts, time sources, serialization interfaces, and type mapping infrastructure.

Compze.Sql.Common

For Compze internal use only. Do not take a direct dependency on this package

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.13.0-alpha 0 11/25/2026
0.12.0-alpha 577 11/14/2026
0.11.0-alpha 161 11/12/2026
0.10.1-alpha 133 11/12/2026
0.10.0-alpha 107 11/12/2026
0.9.1-alpha 71 11/12/2026
0.9.0-alpha 580 7/24/2026
0.8.0-alpha 266 7/15/2026
0.7.0-alpha 261 7/5/2026
0.6.0-alpha 126 7/4/2026
0.5.0-alpha 749 6/4/2026
0.3.0-alpha 109 3/4/2026

- **`LazyCE<TValue>` moves here from Compze.Internals.SystemCE,** in the namespace `Compze.Threading`, so that applications can use it from a package meant to be referenced: a value its factory creates the first time it is read, which improves on `Lazy<T>` where `Lazy<T>` gets in the way. A factory that throws runs again on the next read instead of its exception being cached for good, a deadlock between factories throws after `LockTimeout.Default` instead of hanging, and an instance is one 32-byte object. It moves as it was, and then changes as the next entry says: see Compze.Internals.SystemCE's changelog, up to 0.5.0-internal, for its earlier history. The README has a section on it.
- **`LazyCE<TValue>` can hold a null value, and lets go of its factory once the value is created.** `TValue` may be a nullable reference type (`where TValue : class?`), and a factory that creates null runs once, as for any other value: before, a null value meant no value yet, so such a factory ran again on every read. The new `IsInitialized` tells a value created null from one not yet created, which `ValueIfInitialized()` can't. An instance is still one 32-byte object: it holds its factory until the value is created and no longer, and that is how it knows the value is created, so from then on the factory, and whatever it captured, can be collected. Creating an instance and reading its value takes as long as before, about 17 ns, and a later read under a nanosecond. A null factory throws an `ArgumentException` when the instance is created, instead of a `NullReferenceException` at the first read.