ConcurrentDictionary and updating values
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
0:41 UTC
Read the original article
Hit count: 1187
Hello,
After searching via Google and coming up empty, I decided to ask the gurus here on StackOverflow.
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:
http://blogs.msdn.com/b/pfxteam/archive/2010/01/08/9945809.aspx
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?
Thank you,
Rick
© Stack Overflow or respective owner