schweppes0x
schweppes0x

Reputation: 320

ConcurrentDictionary<string,ArrayList> AddOrUpdate error

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:

  1. Try adding message to arraylist in the ConcurrentDictionary.
  2. If arraylist DOES NOT exist, create a new one with the message in it.
  3. If arraylist DOES exist, simply add it to the end of the array.

So my question is, how can I fix this error and improve my code, what am I doing wrong ?

Upvotes: 0

Views: 241

Answers (1)

schweppes0x
schweppes0x

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

Related Questions