"Be aware of issues with the lock statement (SyncLock in Visual Basic). It is tempting to use the lock statement to solve all threading problems. However, the System.Threading.Interlocked Class is superior for updates that must be made atomically. It executes a single lock prefix if there is no contention. In a code review, you should watch out for instances like the one shown in the following example.
[Visual Basic]
SyncLock Me
myField += 1
End SyncLock
[C#]
lock(this)
{
myField++;
}
Alternatively, it might be better to use more elaborate code to create rhs outside of the lock, as in the following example. Then, you can use an interlocked compare exchange to update x only if it is still null. This assumes that creation of duplicate rhs values does not cause negative side effects.
[Visual Basic]
If x Is Nothing Then
SyncLock Me
If x Is Nothing Then
' Perform some elaborate code to create rhs.
x = rhs
End If
End SyncLock
End If
[C#]
if (x == null)
{
lock (this)
{
if (x == null)
{
// Perform some elaborate code to create rhs.
x = rhs;
}
}
}
"
To make the topic more clear, replace the previous text with the
following:
"Be aware of issues with the lock statement (SyncLock in Visual Basic). It is tempting to use the lock statement to solve all threading problems. However, the System.Threading.Interlocked Class is superior for updates that must be made automatically. This class executes a single lock prefix if there is no contention. For example, in a code review, you should watch out for instances like the one shown in the following example:
[Visual Basic]
SyncLock Me
myField += 1
End SyncLock
[C#]
lock(this)
{
myField++;
}
Replace the previous sample code with the following sample code to improve performance:
[Visual Basic]
System.Threading.Interlocked.Increment(myField)
[C#]
System.Threading.Interlocked.Increment(ref myField);
Another example is to update an object type variable only if the variable is
null. You can use the following code to update the variable and to
make the code thread safe:
[Visual Basic]
If x Is Nothing Then
SyncLock Me
If x Is Nothing Then
x = y
End If
End SyncLock
End If
[C#]
if (x == null)
{
lock (this)
{
if (x == null)
{
x = y;
}
}
}
For this sample, you can improve the performance if you use the
following code to replace the previous code:
[Visual Basic]
System.Threading.Interlocked.CompareExchange(x, y, Nothing)
[C#]
System.Threading.Interlocked.CompareExchange(ref x, y, null);
"