Reputation: 1101
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);
}
Upvotes: 6
Views: 137
Reputation: 89705
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
Upvotes: 1