I'm trying to use a ConcurrentDictionary to help with a filtering task.
If a number appears in list, then I want to copy an entry from one dictionary to another.
But this part of the AddOrUpdate is not right - v.Add(number)
I get
"Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'
And two more errors.
class Program
{
static void Main(string[] args)
{
Program p = new Program();
List<int> filter = new List<int> {1,2};
p.Filter(filter);
}
private void Filter(List<int> filter)
{
Dictionary<string, List<int>> unfilteredResults = new Dictionary<string, List<int>>();
unfilteredResults.Add("key1", new List<int> { 1,2,3,4,5});
ConcurrentDictionary<string, List<int>> filteredResults = new ConcurrentDictionary<string, List<int>>();
foreach (KeyValuePair<string, List<int>> unfilteredResult in unfilteredResults)
{
foreach (int number in unfilteredResult.Value)
{
if (filter.Contains(number))
{
filteredResults.AddOrUpdate(unfilteredResult.Key, new List<int> { number }, (k, v) => v.Add(number));
}
}
}
}
}
It is thread safe in your usage. It becomes not thread safe when the delegate passed to AddOrUpdate has side effects, because those side effects may be executed twice for the same key and existing value.
ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.
The GetOrAdd function The vast majority of methods it exposes are thread safe, with the notable exception of one of the GetOrAdd overloads: TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory); This overload takes a key value, and checks whether the key already exists in the database.
Thanks to Lucas Trzesniewski, for pointing out my mistake in the comments - he didn't want to post an answer.
You probably mean: (k, v) => { v.Add(number); return v; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With