memorybarrier

When to use lock vs MemoryBarrier in .NET

In .NET the lock keyword is syntactic sugar around Monitor.Enter and Monitor.Exit, so you could say that this code lock(locker) { // Do something } is the same as Monitor.Enter(locker); try { // Do Something } finally { Monitor.Exit(locker); } However the .NET framework also includes the MemoryBarrier class which works in a s...

Memory Barrier by lock statement

I read recently about memory barrier and the reordaring issue and now I have some confusion about it. Let us have a following senario: private object _object1 = null; private object _object2 = null; private bool _usingObject1 = false; private object MyObject { get { if (_usingObject1) { return _o...

Why do I need a memorybarrier

C# 4 in a Nutshell (highly recommended btw) uses the following code to demonstrate the concept of MemoryBarrier (assuming A and B were run on different threads): class Foo{ int _answer; bool complete; void A(){ _answer = 123; Thread.MemoryBarrier(); // Barrier 1 _complete = true; Thread.MemoryBarrier(); // Barrier ...