Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for Interlocked.Exchange in property setter

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
like image 569
Eslam Sameh Ahmed Avatar asked Mar 10 '23 20:03

Eslam Sameh Ahmed


2 Answers

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.

like image 111
Douglas Avatar answered May 03 '23 05:05

Douglas


Interlocked.Exchange(Me._Status, value)

  1. It's already a one-liner, how much shorter do you think it can get?

  2. 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.

like image 30
Henk Holterman Avatar answered May 03 '23 04:05

Henk Holterman