【问题标题】:Shorthand for Interlocked.Exchange in property setter属性设置器中 Interlocked.Exchange 的简写
【发布时间】:2017-03-05 07:09:04
【问题描述】:

我有以下简单的变量声明一个由反编译器生成的类

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

此声明是否有任何简写形式。 实际上这是在类内部使用 backgroundworker 并由另一个类从外部访问。

要明确速记是什么意思。我举个例子: 下面的神是速记

SyncLock lock
    z = 1
End SyncLock

以下详细代码

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

【问题讨论】:

    标签: .net vb.net decompiling decompiler shorthand


    【解决方案1】:

    Interlocked.Exchange(Me._Status, value)

    1. 已经是单线了,你觉得还能短多少?

    2. 使用 Exchange(Int32) 的唯一好处是它会导致内存屏障。因此,当您更喜欢它时,可以将其替换为您的示例 SyncLock 以获得相同的效果。

    【讨论】:

    • 但 SyncLock 会反编译为问题中提到的不同语法。
    • 所以,反编译器做出选择。
    【解决方案2】:

    正如 Holterman 所提到的,Interlocked.Exchange 提供的唯一好处是内存屏障。 (Int32 分配在 .NET 中始终是原子的,而您正在丢弃返回值。)

    如果源代码是用 C# 编写的,则它最初可能包含 volatile 关键字,这也会产生内存屏障。

    private volatile int _Status;
    public int Status
    {
        get { return _Status; }
        set { _Status = value; }
    }
    

    但是,这应该会导致在 getter 中生成内存屏障。

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2021-06-06
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多