Reputation: 320
I stumbled upon the following obstacle. I need to have a ConcurrentDictionary<string, ArrayList> which has string as key and ArrayList as value. I want to use the AddOrUpdate in the following manner:
using System.Collections;
using System.Collections.Concurrent;
private ConcurrentDictionary<string, ArrayList> _data= new ConcurrentDictionary<string, ArrayList>();
private void AddData(string key, string message){
_data.AddOrUpdate(key, new ArrayList() { message }, (string existingKey, string existingList) => existingList.Add(message));
}
However this method does not work and throws the following error:
Compiler Error CS1661: Cannot convert anonymous method block to delegate type 'delegate type' because the specified block's parameter types do not match the delegate parameter types
See link to error
In conclusion, I am trying to do the following:
So my question is, how can I fix this error and improve my code, what am I doing wrong ?
Upvotes: 0
Views: 241
Reputation: 320
The correct thread-safe way is:
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
private ConcurrentDictionary<string, List<string>> _data = new ConcurrentDictionary<string, List<string>();
private void AddData(string key, string message){
var list = _data.GetOrAdd(key, _ => new List<string>());
lock(list)
{
list.Add(message);
}
}
Upvotes: 1