I have the following simple piece of variable declaration a class with generated by a decompiler
Friend Class Project
Private _Status As Integer
Public Property Status As Integer
Get
Return Me._Status
End Get
Set(ByVal value As Integer)
Interlocked.Exchange(Me._Status, value)
End Set
End Property
End Class
Is there is any shorthand form for this declaration. Actually this is used internally backgroundworker inside the class and accessed externally by another classes.
To be clear in what is the meaning of shorthand. I will give an example: The following gode is a shorthand
SyncLock lock
z = 1
End SyncLock
for the following detailed code
Dim obj As Object = Me.lock
ObjectFlowControl.CheckForSyncLockOnValueType(obj)
Dim flag As Boolean = False
Try
Monitor.Enter(obj, flag)
Me.z = 1
Finally
If (flag) Then
Monitor.[Exit](obj)
End If
End Try
As Holterman has mentioned, the only benefit that the Interlocked.Exchange
provides is the memory barrier. (Int32
assignments are always atomic in .NET, and you're discarding the return value.)
If the source code had been written in C#, it is possible that it originally contained the volatile
keyword, which also generates memory barriers.
private volatile int _Status;
public int Status
{
get { return _Status; }
set { _Status = value; }
}
However, this should have resulted in a memory barrier being generated in the getter as well.
Interlocked.Exchange(Me._Status, value)
It's already a one-liner, how much shorter do you think it can get?
The only benefit from using Exchange(Int32) is the memory barrier it causes. So when you like it better, you can replace it by your sample SyncLock
for the same effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With