如何使用 ConcurrentDictionary(of Integer, Class).TryUpdate?
How to use ConcurrentDictionary(of Integer, Class).TryUpdate?
用新值更新 ConcurrentDictionary 的正确方法是什么?我正在尝试 AllWidgets.TryUpdate(id, myWidget, myWidget) 并且它 returns 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 为假
我想我真的不明白第三个参数应该如何用于复杂对象。
这样你永远不会得到 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 return:
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
用新值更新 ConcurrentDictionary 的正确方法是什么?我正在尝试 AllWidgets.TryUpdate(id, myWidget, myWidget) 并且它 returns 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 为假
我想我真的不明白第三个参数应该如何用于复杂对象。
这样你永远不会得到 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 return:
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