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?
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:
Note that there is no real replacement forvolatile
in VB.NET, becausevolatile
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
or in VB.NET: