更新维度并发字典

时间:2014-11-12 21:47:26

标签: vb.net

我找到了这个小功能,但是我很难尝试正确调用它。如何调用它来更新我的ConcurrentDictionary

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim Animals As New Concurrent.ConcurrentDictionary(Of String, String())
        Dim iKey = "key123456"

        Animals(iKey) = {"cat", "dog", "bird"}

        Dim success As Boolean = TryUpdate(Animals, iKey, Func("cat", "frog"))
    End Sub

    Function TryUpdate(Of TKey, TValue)(dict As Concurrent.ConcurrentDictionary(Of TKey, TValue), key As TKey, updateFactory As Func(Of TValue, TValue)) As Boolean
        Dim curValue As TValue
        If Not dict.TryGetValue(key, curValue) Then
            Return False
        End If
        dict.TryUpdate(key, updateFactory(curValue), curValue)
        Return True
    End Function
End Class

1 个答案:

答案 0 :(得分:2)

TryUpdate有三个参数,

  1. 要更新的ConcurrentDictionary,
  2. 要在字典中更新的密钥,
  3. 委托函数,接受密钥的当前值,并返回所需的值。

    Dim success As Boolean = TryUpdate(myDictionary, myKey, Func(oldval) newval)
    
  4. 你如何传递第三个参数取决于你,但看起来意图是这样你可以查看旧值以确保它符合你的预期,然后传递新值或返回值因此。


    为了清晰起见:第三个参数是期望将一个委托传递给一个函数,该函数将接受您尝试更改的键的当前值,并返回一个新值(或者原始值,如果您不&# 39;我想改变它。)

    在这里,我创建了一个函数CheckValue,用于确定旧值是否符合我的预期,如果是,则返回新值。 myDel是该函数的委托,传递给TryUpdate

    Dim whatIExpected As String = ""
    Dim newVal As String = ""
    Dim myDel As Func(Of String, String) = AddressOf CheckValue
    Public Function CheckValue(ByVal oldVal As String) As String
        If (oldVal = whatIExpected) Then
            Return newVal
        Else
            Return oldVal
        End If
    End Function
    
    'Then later inside some function or sub..
    whatIExpected = "cat"
    newVal = "frog"
    Dim success As Boolean = TryUpdate(myDictionary, myKey, myDel)