Why is Thread.MemoryBarrier used here?

Looking through the MEF source code, I found this snippet. Can someone explain why the MemoryBarrier needed inside the castle?

The whole method:

 public void SatisfyImportsOnce(ComposablePart part) { this.ThrowIfDisposed(); if (this._importEngine == null) { ImportEngine importEngine = new ImportEngine(this, this._compositionOptions); lock(this._lock) { if (this._importEngine == null) { Thread.MemoryBarrier(); this._importEngine = importEngine; importEngine = null; } } if(importEngine != null) { importEngine.Dispose(); } } this._importEngine.SatisfyImportsOnce(part); } 
+6
source share
1 answer

Thread.MemoryBarrier prevents jitter / compiler transcoding to optimize code.

In Advancing in C #, by Joe Albahari , he says:

  • The compiler, CLR, or CPU can reorder your program instructions to increase efficiency.
  • A compiler, CLR, or CPU can create caching optimizations, so variable assignments will not immediately be visible to other threads.

This example may indicate that the values โ€‹โ€‹of importEngine or _importEngine are cached, and it is very important that all threads are immediately notified of changes.

In addition, the MemoryBarrier in this case provides a guarantee of freshness of importEngine before assigning _importEngine

+1
source

All Articles