S2445 — Blocks should be synchronized on read-only fields

Language
C#
Type
Bug
Severity
Major
Tags
cwe, multi-threading

Why is this an issue?

Locking on a class field synchronizes not on the field itself, but on the object assigned to it. Thus, there are some good practices to follow to avoid problems related to thread synchronization.

How to fix it

Code examples

Noncompliant code example


private Color color = new Color("red");
private void DoSomething()
{
  // Synchronizing access via "color"
  lock (color) // Noncompliant: lock is actually on object instance "red" referred to by the "color" field
  {
    //...
    color = new Color("green"); // other threads now allowed into this block
    // ...
  }
}

Compliant solution


private Color color = new Color("red");
private readonly object lockObj = new object();

private void DoSomething()
{
  lock (lockObj)
  {
    //...
    color = new Color("green");
    // ...
  }
}

Resources

↑ Back to top