如何使用ConcurrentDictionary(Integer,Class).TryUpdate?

时间:2015-02-06 16:47:11

标签: vb.net concurrentdictionary

使用新值更新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是假的

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

1 个答案:

答案 0 :(得分:1)

你永远不会这样。您要做的第一件事是使Widgets可比,覆盖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可以比较小部件。你会以这种方式获得真正的回报:

    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