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

108 Views Asked by At

According to Web, I found the following codes, which is equivalent of C# Volatile for VB.NET.

Code reference: 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

I want to know exactly, What does Threading.Thread.MemoryBarrier() do and how, when I execute it in above code ?

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

1

There are 1 best solutions below

2
On BEST ANSWER

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

Yes... By looking at this table http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

you can see that if you do a volatile read and a volatile write, you'll have the equivalent effect. So:

private volatile static int Useless = 0;

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

Note that there is no real replacement for volatile in VB.NET, because volatile fields use "half" memory barriers, not "full" memory barriers, while the methods that was suggested in that response uses a "full" memory barrier, so it is slower.

From .NET 4.5, you can simulate it in VB.NET by using Volatile.Read and Volatile.Write

public static void MemoryBarrier()
{
    int useless = 0;
    int temp = Volatile.Read(ref useless);
    Volatile.Write(ref useless, temp);
}

or in VB.NET:

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