2015-02-06 63 views
1

用新值更新ConcurrentDictionary的正確方法是什麼?我想AllWidgets.TryUpdate(ID,進myWidget,進myWidget),它返回false,不會在這種類型的情況下正確更新:如何使用ConcurrentDictionary(整數,類).TryUpdate?

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

你永遠不會得到真正的這種方式。你必須做的第一件事是使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 
相關問題