Browsing through the MEF source code I found this piece.
Can somebody explain why MemoryBarrier
is needed inside a lock?
The whole method is:
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);
}
Thread.MemoryBarrier prevents jitter/compiler any instructions reordering for code optimization.
In Treading in C#, by Joe Albahari book he sais:
In this example it might be that importEngine or _importEngine values are cached and it is very important that all threads has to be notified about changes right away.
Also MemoryBarrier in this case provides importEngine freshness garantee before it assigned to _importEngine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With