Updating fields of values in a ConcurrentDictionary

后端 未结 3 1419
执笔经年
执笔经年 2020-12-18 22:33

I am trying to update entries in a ConcurrentDictionary something like this:

class Class1
{
    public int Counter { get; set; }
}

class Test
{
    private          


        
3条回答
  •  伪装坚强ぢ
    2020-12-18 23:22

    ConcurrentDictionary doesn't help you with accessing members of stored values concurrently, just with the elements themselves.

    If multiple threads call TestIt, you should get a snapshot of the collection and lock the shared resources (which are the individual dictionary values):

    foreach (KeyValuePair kvp in dict.ToArray())
    {
        Class1 value = kvp.Value;
        lock (value)
        {
            value.Counter = value.Counter + 1;
        }
    }
    

    However, if you want to update the counter for a specific key, ConcurrentDictionary can help you with atomically adding a new key value pair if the key does not exist:

    Class1 value = dict.GetOrAdd(42, key => new Class1());
    lock (value)
    {
        value.Counter = value.Counter + 1;
    }
    

    AddOrUpdate and TryUpdate indeed are for cases in which you want to replace the value for a given key in a ConcurrentDictionary. But, as you said, you don't want to change the value, you want to change a property of the value.

提交回复
热议问题