diff --git a/analyzers/rspec/cs/S2445_c#.html b/analyzers/rspec/cs/S2445_c#.html index b7bbc9cb9d8..fc6dc281284 100644 --- a/analyzers/rspec/cs/S2445_c#.html +++ b/analyzers/rspec/cs/S2445_c#.html @@ -3,31 +3,37 @@ the new value, to enter the block at the same time.
Locking on a readonly
field of a class which is not private
allows external code to lock the field, potentially
interfering with synchronization of methods in that class.
Locking on a local variable or on a new instance undermines the synchronization: two different threads running the method in parallel would lock on -two different object instances.
+Locking on a local variable or on a new instance undermines the synchronization: two different threads running the same method in parallel would +lock on two different object instances. That would allow a second thread, locked on that new value, to enter the same block concurrently.
Locking on a string literal is even more dangerous: depending on whether the string is interned or not, different threads may or may not synchronize on the same object instance.
-private string color = "red"; +private Color colorObject = new Color("red"); +private readonly colorString = "red"; private void DoSomething() { - lock (color) // Noncompliant; lock is actually on object instance "red" referred to by the color variable + // Synchronizing access via "colorObject" + lock (colorObject) // Noncompliant; lock is actually on object instance "red" referred to by the color field { //... - color = "green"; // other threads now allowed into this block + colorObject = new Color("green"); // other threads now allowed into this block // ... } - lock (new object()) // Noncompliant this is a no-op. + lock (new object()) // Noncompliant; this is a no-op { - // ... + // ... + } + lock (colorString) // Noncompliant; strings can be interned + { + // ... } }
-private string color = "red"; +private Color colorObject = new Color("red"); private readonly object lockObj = new object(); private void DoSomething() @@ -35,7 +41,7 @@Compliant Solution
lock (lockObj) { //... - color = "green"; + color = new Color("green"); // ... } }