ConcurrentDictionary<string,ArrayList> AddOrUpdate error



我偶然发现了以下障碍。我需要一个ConcurrentDictionary它以string作为键,以ArrayList作为值。我想以以下方式使用AddOrUpdate:

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));
}

但是此方法不起作用并抛出以下错误:

编译错误CS1661:无法将匿名方法块转换为委托类型'委托类型',因为指定块的参数类型与委托参数类型不匹配

见错误链接

总之,我正在努力做以下事情:

  1. 尝试将消息添加到ConcurrentDictionary中的arraylist中。
  2. 如果arraylist不存在,创建一个包含消息的新数组。
  3. 如果arraylist确实存在,只需将其添加到数组的末尾。

我的问题是,我怎么能修复这个错误和提高我的代码,我做错了什么?

正确的线程安全方法是:

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);
} 
}

最新更新