A field is initialized with double-checked locking but is not volatile, so another thread can see it half built

tx0/csharp:double-checked-lock-not-volatilestrictwarningreliability/concurrencydepth fastbug, cwe-609

What it finds

In if (instance == null) { lock (gate) { if (instance == null) instance = new T(); } } the first test runs without the lock. Without volatile, the write of the reference may become visible to another thread before the writes of the constructor, which then uses an object whose fields are not yet set. Lazy<T> or LazyInitializer do this correctly. The rule reports the assignment in that pattern to a field of the same type declared without volatile. The memory model of the .NET runtime on current hardware makes the pattern work without it in practice, which is why the rule is strict.

From the rule's source, double_checked_lock_not_volatile.rs.

Example from the rule's tests
class Registry{    private static Registry instance;    private static volatile Registry safe;    private static readonly object gate = new object();     static Registry Get()    {        if (instance == null)        {            lock (gate)            {                if (instance == null)                {                    instance = new Registry();tx0 reports: instance is published by double-checked locking but is not volatile                }            }        }        if (safe == null)        {            lock (gate)            {                if (safe == null)                {                    safe = new Registry();                }            }        }        return instance;    }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:double-checked-lock-not-volatile" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/csharp:double-checked-lock-not-volatile] reason="..."

tx0 explain tx0/csharp:double-checked-lock-not-volatile shows the same in the terminal. Found a false positive? Report it.