S6507 — Blocks should not be synchronized on local variables

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

Why is this an issue?

Locking on a local variable can undermine synchronization because two different threads running the same method in parallel will potentially lock on different instances of the same object, allowing them to access the synchronized block at the same time.

Noncompliant code example


private void DoSomething()
{
  object local = new object();
  // Code potentially modifying the local variable ...

  lock (local) // Noncompliant
  {
    // ...
  }
}

Compliant solution


private readonly object lockObj = new object();

private void DoSomething()
{
  lock (lockObj)
  {
    //...
  }
}

Resources

↑ Back to top