The following rules outline the design guidelines for implementing threading:
SyncLock Me myField += 1 End SyncLock [C#] lock(this) { myField++; }
If you replace the previous example with the following one, you will improve performance.
System.Threading.Interlocked.Increment(myField) [C#] System.Threading.Interlocked.Increment(myField);
Another example is to update an object type variable only if it is null (Nothing in Visual Basic). You can use the following code to update the variable and make the code thread safe.
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; } } }
You can improve the performance of the previous sample by replacing it with the following code.
System.Threading.Interlocked.CompareExchange(x, y, Nothing) [C#] System.Threading.Interlocked.CompareExchange(ref x, y, null);
Design Guidelines for Class Library Developers | Visual Basic Language Changes | System.Threading Namespace