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

[source,csharp]
----
private void DoSomething()
{
  object local = new object();
  // Code potentially modifying the local variable ...

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


== Compliant Solution

[source,csharp]
----
private readonly object lockObj = new object();

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

== See

* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock[Lock Statement] - lock statement - ensure exclusive access to a shared resource
* https://cwe.mitre.org/data/definitions/412[MITRE, CWE-412] - Unrestricted Externally Accessible Lock
* https://cwe.mitre.org/data/definitions/413[MITRE, CWE-413] - Improper Resource Locking

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::message.adoc[]

include::highlighting.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]
