A lock takes an object that other code can lock too: this, a type or a string
What it finds
lock (this), lock (typeof(Cache)) and lock ("name") lock objects that any other code can reach and lock as well: strings are interned and types are shared across the process. Unrelated code then contends for the same lock or deadlocks with it. A private object used only as a lock is safe.
From the rule's source, lock_on_weak_identity.rs.
class Cache{ private readonly object gate = new object(); void Update() { lock (this)tx0 reports: locking this, which other code can lock as well { } lock (typeof(Cache))tx0 reports: locking a type object, which other code can lock as well { } lock ("cache")tx0 reports: locking a string literal, which other code can lock as well { } lock (gate) { } }} 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:
[rules]
"tx0/csharp:lock-on-weak-identity" = "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-weak-identity] reason="..."tx0 explain tx0/csharp:lock-on-weak-identity shows the same in the terminal. Found a false positive? Report it.