Locking on a class field synchronizes not on the field itself, but on the object assigned to it. Thus, there are some good practices to follow to avoid problems related to thread synchronization.
readonly field makes it possible for the field’s value to change while a thread is in the code block, locked on the old value. This allows another thread to lock on the new value and access the same block concurrently.
private Color color = new Color("red");
private void DoSomething()
{
// Synchronizing access via "color"
lock (color) // Noncompliant: lock is actually on object instance "red" referred to by the "color" field
{
//...
color = new Color("green"); // other threads now allowed into this block
// ...
}
}
private void DoSomething()
{
lock (new object()) // Noncompliant: every thread locks on a different new instance
{
// ...
}
}
private readonly string colorString = "red";
private void DoSomething()
{
lock (colorString) // Noncompliant: strings can be interned
{
// ...
}
}
private Color color = new Color("red");
private void DoSomething()
{
// Synchronizing access via "color"
lock (color) // Noncompliant: lock is actually on object instance "red" referred to by the "color" field
{
//...
color = new Color("green"); // other threads now allowed into this block
// ...
}
}
private Color color = new Color("red");
private readonly object lockObj = new object();
private void DoSomething()
{
lock (lockObj)
{
//...
color = new Color("green");
// ...
}
}
String.Intern(String) Method