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
source share