Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
Assembly: mscorlib (in mscorlib.dll)
Public Shared Sub MemoryBarrier
public static void MemoryBarrier()
public: static void MemoryBarrier()
static member MemoryBarrier : unit -> unit
MemoryBarrier is required only on multiprocessor systems with weak memory ordering (for example, a system employing multiple Intel Itanium processors).
For most purposes, the C# lock statement, the Visual Basic SyncLock statement, or the Monitor class provide easier ways to synchronize data.
.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1.NET Framework Client Profile
Supported in: 4, 3.5 SP1Portable Class Library
Supported in: Portable Class LibraryWindows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Reference
complete variable is cached in a CPU register. Inserting a call to Thread.MemoryBarrier inside the while loop (or lockingaround reading complete) fixes the error.$0
$0$0
$0an abstract from albahari's blog on threading$0
$0
static void Main()
{
bool complete = false;
var t = new Thread(() =>
{
bool toggle = false;
while(!complete)
toggle = !toggle;
})
t.Start();
Thread.Sleep(1000);
complete = true;
t.Join(); // Blocks indefinitely
}
If you run this with optimizations enabled and no debugger the app will not terminate because the complete variable is cached!