1

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?

Community
  • 1
  • 1
Behzad
  • 3,502
  • 4
  • 36
  • 63

1 Answers1

4

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
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • thank u really about that [like](http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/) but i don't understand what is the your code means ? I want to know MemoryBarrier how to work ? – Behzad Jun 11 '15 at 17:13
  • 1
    @BehzadKhosravifar An explanation of what does `volatile` means and what a `MemoryBarrier` is is quite complex *and* technical. It is better if you read the "Good place to start" link they gave you and if necessary you put specific questions. – xanatos Jun 12 '15 at 06:36