How to utilize double check locking in C# correctly

The major benefit of double check locking is to reduce the overhead of acquiring a lock by first testing the locking in an unsafe manner under a multi-threaded environment. It is widely used in the scenarios such as lazy initialization. Typical pseudo code would be like followings:

IF (VAR_X meets certain conditions)



       IF (VAR_X meets certain conditions)


                   VAR_X = NEW_VAR_X;






Unfortunately, due to the aggressive optimization of modern compiler, thread A might possibly access partial result of VAR_X before thread B actually completes updating it. As a result, the app will probably crash.

In C#, to ensure the correctness, we should declare VAR_X as volatile to ensure the assignment to the VAR_X completes before it can be accessed. I am working on a sample to demonstrate this; Can anyone share working code before I post my version out?

Singleton implementation in msdn:

Comments (6)

  1. int19h says:

    The annoying part of it is that C# disallows "volatile" for local variables, even though they can perfectly well be accessed concurrently.

  2. MichaelGG says:

    You can do a MemoryBarrier directly which can be more efficient overall…

  3. Note that your example is incorrect. The new_var_x needs to be stored to a local, then fully initialized, and only then can it be stored to VAR_X. Otherwise, you have the problem of VAR_X containing a partially initialized object.

  4. MSDN Archive says:

    Thanks for the comment. It is a great post containing informative discussion. Although people agreed on volatile implementation, I find I have troubles in figuring out which one is the correct implementations for MemoryBarrier. Specifically do we need MemoryBarrier for both reads and writes?


  5. MSDN Archive says:

    That is why I call it pseudo code. 🙂

Skip to main content