The instance passed to the https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock[`lock` statement] should be a dedicated private field.

include::../why-dotnet.adoc[]

The following objects are considered potentially prone to accidental lock sharing:

* a reference to https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this[this]: if the instance is publicly accessibly, the lock might be shared
* a https://learn.microsoft.com/en-us/dotnet/api/system.type[Type] object: if the type class is publicly accessibly, the lock might be shared
* a https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/[string] literal or instance: if any other part of the program uses the same string, the lock is shared because of interning

== How to fix it

=== Code examples

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
void MyLockingMethod()
{
    lock (this) // Noncompliant
    {
        // ...
    }
}
----

==== Compliant solution

[source,csharp,diff-id=1,diff-type=compliant]
----
#if NET9_0_OR_GREATER
private readonly Lock lockObj = new();
#else
private readonly object lockObj = new();
#endif

void MyLockingMethod()
{
    lock (lockObj)
    {
        // ...
    }
}
----

include::../resources-dotnet.adoc[]

* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock[The lock statement - ensure exclusive access to a shared resource]

include::../rspecator.adoc[]
