【问题标题】:How to use ConcurrentDictionary(of Integer, Class).TryUpdate?如何使用 ConcurrentDictionary(of Integer, Class).TryUpdate?
【发布时间】:2015-02-06 16:47:10
【问题描述】:

用新值更新 ConcurrentDictionary 的正确方法是什么?我正在尝试 AllWidgets.TryUpdate(id, myWidget, myWidget) 并且它返回 false 并且在这种情况下无法正确更新:

Public Class Widget
    Public ID As Integer
    Public Name As String
    Public Sub New(ByVal id As Integer, ByVal name As String)
        ID = id
        Name = name
    End Sub
End Class

Dim AllWidgets As New ConcurrentDictionary(Of Integer, Widget)
AllWidgets.TryAdd(1, New Widget(1000, "Widget A"))
AllWidgets.TryAdd(2, New Widget(1001, "Widget B"))

Dim UpdateWidget As New Widget(1001, "Widget BB")
Dim IsUpdated As Boolean = AllWidgets.TryUpdate(2, UpdateWidget, UpdateWidget)

IsUpdated 为假

我想我真的不明白第三个参数应该如何用于复杂对象。

【问题讨论】:

    标签: vb.net concurrentdictionary


    【解决方案1】:

    这样你永远不会得到 True。您要做的第一件事是使 Widget 具有可比性,覆盖 GetHashCode() 和 Equals()。像这样:

    Public Class Widget
        ''...
        Public Overrides Function GetHashCode() As Integer
            Return Me.ID.GetHashCode() Xor Me.Name.GetHashCode()
        End Function
    
        Public Overrides Function Equals(obj As Object) As Boolean
            Dim w = CType(obj, Widget)
            Return w.ID = Me.ID AndAlso w.Name = Me.Name
        End Function
    End Class
    

    现在 ConcurrentDictionary 可以比较小部件。您将通过这种方式获得 True 回报:

        Dim UpdateWidget As New Widget(1001, "Widget BB")
        Dim OldWidget As New Widget(1001, "Widget B")
        Dim IsUpdated As Boolean = AllWidgets.TryUpdate(2, UpdateWidget, OldWidget)
        Debug.Assert(IsUpdated)   '' fine
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2022-12-27
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多