Updating fields of values in a ConcurrentDictionary

Posted by rboarman on Stack Overflow See other posts from Stack Overflow or by rboarman
Published on 2010-05-25T00:38:16Z Indexed on 2010/05/25 1:01 UTC
Read the original article Hit count: 715

Filed under:
|
|

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

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

class Test
{
    private ConcurrentDictionary<int, Class1> dict =
        new ConcurrentDictionary<int, Class1>();

    public void TestIt()
    {
        foreach (var foo in dict)
        {
            foo.Value.Counter = foo.Value.Counter + 1; // Simplified example
        }
    }
}

Essentially I need to iterate over the dictionary and update a field on each Value. I understand from the documentation that I need to avoid using the Value property. Instead I think I need to use TryUpdate except that I don’t want to replace my whole object. Instead, I want to update a field on the object.

After reading this blog entry on the PFX team blog: Perhaps I need to use AddOrUpdate and simply do nothing in the add delegate.

Does anyone have any insight as to how to do this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about concurrency