当我 运行 MemoryBarrier() 时会发生什么?怎么办?

What happen when I run MemoryBarrier() exactly ? and how do it?

根据Web查到如下代码,相当于C# Volatile for VB.NET.

代码参考:How do I specify the equivalent of volatile in VB.net?

Function VolatileRead(Of T)(ByRef Address As T) As T
    VolatileRead = Address
    Threading.Thread.MemoryBarrier() '*** I mean this line ***'
End Function

Sub VolatileWrite(Of T)(ByRef Address As T, ByVal Value As T)
    Threading.Thread.MemoryBarrier() '*** I mean this line ***'
    Address = Value
End Sub

我想确切地知道,当我在上面的代码中执行它时,Threading.Thread.MemoryBarrier() 做了什么以及如何做?

我可以自己用 C# 编写等同于 MemoryBarrier() 的方法吗?

Can I write a method equivalent to MemoryBarrier() in C# myself?

是的...通过查看此 table http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

您可以看到,如果您执行易失性读取 易失性写入,您将获得相同的效果。所以:

private volatile static int Useless = 0;

public static void MemoryBarrier()
{
    int temp = Useless;
    Useless = temp;
}

请注意,VB.NET 中 volatile 没有真正的替代品,因为 volatile 字段使用 "half" 内存屏障,而不是 "full" 内存屏障,而该响应中建议的方法使用 "full" 内存屏障,因此速度较慢。

从 .NET 4.5 开始,您可以使用 Volatile.Read and Volatile.Write

在 VB.NET 中模拟它
public static void MemoryBarrier()
{
    int useless = 0;
    int temp = Volatile.Read(ref useless);
    Volatile.Write(ref useless, temp);
}

或 VB.NET:

Public Shared Sub MemoryBarrier()
    Dim useless As Integer = 0
    Dim value As Integer = Volatile.Read(useless)
    Volatile.Write(useless, value)
End Sub