I have no idea why the author decided to use locking in one part of the class, while using locking technologies in other parts. However, I can assume that the author did this to create an explicit memory barrier when reading Interger . VB does not contain the C # volatile keyword equivalent, so it leaves only 4 other common methods for safe reading. I listed them in the order that I would choose for this particular scenario.
- Interlocked.CompareExchange
- Thread.VolatileRead
- Thread.MemoryBarrier
- Synclock
A memory lock is required to prevent the VB or JIT compiler. The most likely optimization in the absence of a memory barrier is to raise reads outside the loop. Consider this realistic use of the ThreadCount property.
Sub LoggingThread() Do While True Trace.WriteLine(ThreadPool.ThreadCount) Loop End Sub
In this example, the CLR will most likely have a ThreadCount built in, and then potentially " _Count up" to read _Count and _Count it in the CPU register before the start of the loop. The effect will be that the same value will always be displayed. one
1 In fact, the call to Trace.WriteLine creates a memory barrier that can lead to code being accidentally safe. The example was intended as a simple illustration of what might happen.
Brian gideon
source share