Udostępnij za pośrednictwem


Thread.MemoryBarrier Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Ensures that memory accesses that appear before the call to MemoryBarrier, in program order, will not execute after the call to MemoryBarrier, and that memory accesses that appear after the call to MemoryBarrier will not execute before that call.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<SecuritySafeCriticalAttribute> _
Public Shared Sub MemoryBarrier
[SecuritySafeCriticalAttribute]
public static void MemoryBarrier()

Remarks

Language compilers, the CPU, and the just in time (JIT) compiler can change the order in which memory is accessed, as long as the reordering does not affect the single-threaded semantics of your code. However, in multithreaded programs such optimizations can affect the outcome and cause errors when threads simultaneously access the same memory. A call to MemoryBarrier prevents any reordering that would move a memory access from one side of the call to the other.

Therefore, language compilers, the CPU, and the JIT compiler will not reorder memory operations (read or write) that appear in your program before the call to MemoryBarrier so that they occur after the call to MemoryBarrier when the program is executed. Similarly, memory accesses that appear in your program after the call will not be executed before the call.

It is difficult to build correct multithreaded programs by using MemoryBarrier. For most purposes, the C# lock statement, the Visual Basic SyncLock statement, and the methods of the Monitor class provide easier and less error-prone ways to synchronize memory accesses. We recommend that you use them instead of MemoryBarrier.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.