Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a dictionary in c# in a multi-threaded environment

I have declared a dictionary of dicionary:

Dictionary<String, Dictionary<String, String>> values;

I have a getter to get a dictionary at a specific index:

public Dictionary<String,String> get(String idx)
{
    lock (_lock)
    {
        return values[moduleName];
    }
}

As you can see I am working in a multi-threaded environment. My question is do I need to return a copy of my dictionary in order to be thread safe like this:

public Dictionary<String,String> get(String idx)
{
    lock (_lock)
    {
        return new Dictionary<string, string>(values[moduleName]);
    }
}

If I don't will the class that calls the getter receive a copy (so if I remove this dictionary from my Dictionary<String, Dictionary<String, String>> will it still work)?

Cheers,

Thierry.

like image 715
Thierry Ybt Avatar asked Jan 24 '12 08:01

Thierry Ybt


1 Answers

Dictionary<> is not Thread-safe, but ConncurrentDictionary<> is.

The class calling the getter receives a reference, which means it will still be there if you remove it from the values-Dictionary as the GC does not clean it as long as you have a reference somewhere, you just can't get it with the getter anymore.

Basicaly that means you have two possibilities when using Dictionary<>:

  • return a copy: Bad idea, because if you change the config you have two different configurations in your app "alive"
  • lock the instance: this would make it thread-safe, but then use ConcurrentDictionary<> as it does exactly that for you
like image 60
Christoph Fink Avatar answered Sep 28 '22 07:09

Christoph Fink