vlad vlad - 1 year ago 76
C# Question

Adding a new item in dictionary from multiple threads

I have a problem adding a new item to a Static dictionary while using it from multiple threads. Any ideas where im doing it wrong?
Initializing the dictionary:

public static class Server
public static volatile Dictionary<int, List<SomeClass>> Values;

Trying to add an item:

Server.Values.Add(someInt, new List<SomeClass> { elements});

Answer Source

As explained by Jon Skeet you are using an object which is not guaranteed to be thread safe

try using ConcurrentDictionary which is designed for Concurrency Scenario With Many threads

public static class Server
    public static  ConcurrentDictionary<int, List<SomeClass>> Values =
                      new ConcurrentDictionary<int, List<SomeClass>>(); 

Here how to use it

bool added = Server.Values.TryAdd(someInt, new List<SomeClass> { elements});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download