Sobes.tech
Middle

There is a static dictionary, and we want to write to it from different threads. How is it best to do this?

sobes.tech AI

Answer from AI

For safe writing to a static dictionary from multiple threads in C#, it is better to use the ConcurrentDictionary<TKey, TValue> class. It is specifically designed for thread-safe collection operations and allows simultaneous reading and writing without locks, which improves performance compared to a regular dictionary with external synchronization.

Example of usage:

using System.Collections.Concurrent;

static class MyStaticClass
{
    private static ConcurrentDictionary<string, int> _dict = new ConcurrentDictionary<string, int>();

    public static void AddOrUpdate(string key, int value)
    {
        _dict.AddOrUpdate(key, value, (k, oldValue) => value);
    }

    public static bool TryGetValue(string key, out int value)
    {
        return _dict.TryGetValue(key, out value);
    }
}

If for some reason you need to use a regular Dictionary, then you will have to wrap access to it in lock blocks, which can lead to blocking and reduced performance.