vlad vlad - 2 months ago 6
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

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