A lock takes a field that is assigned again outside the constructors, so threads may lock different objects

tx0/csharp:lock-on-mutable-fieldrecommendedwarningreliability/concurrencydepth fastbug

What it finds

Two threads exclude each other only when they lock the same object. If the locked field can be reassigned, a thread that reads it after the change locks the new object while another still holds the old one, and both run the protected code at once. The rule reports lock on a field declared in the same type without readonly and assigned outside its declaration and the constructors.

From the rule's source, lock_on_mutable_field.rs.

Example from the rule's tests
class Cache{    private object gate = new object();    private readonly object fixedGate = new object();     private object stable = new object();     void Update()    {        lock (gate)tx0 reports: gate is assigned again elsewhere, so the locked object can change        {        }        lock (stable)        {        }        lock (fixedGate)        {        }    }     void Reset()    {        gate = new object();    }}
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 recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:lock-on-mutable-field" = "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:lock-on-mutable-field] reason="..."

tx0 explain tx0/csharp:lock-on-mutable-field shows the same in the terminal. Found a false positive? Report it.