rspec/rules/S2551/csharp/rule.adoc
kevin.hinz 7bb601b5d7
Modify rule S2551: clarify example used in the description (#3713)
* Modify rule S2551: clarify example in description

* Modify rule S2551: improve word choice
2024-03-15 14:40:37 +01:00

49 lines
1.5 KiB
Plaintext

include::../why-dotnet.adoc[]
For example, a `string` should never be used for locking. When a `string` is https://en.wikipedia.org/wiki/Interning_(computer_science)[interned] by the runtime, it can be shared by multiple threads, breaking the locking mechanism.
Instead, a dedicated private `object` instance should be used for each shared resource. This minimizes access to the lock instance, avoiding deadlocks and lock contention.
The following objects are considered as shared resources:
* 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]
----
private readonly object lockObj = new object();
void MyLockingMethod()
{
lock (lockObj)
{
// ...
}
}
----
include::../resources-dotnet.adoc[]
include::../rspecator.adoc[]