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.
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<>
:
ConcurrentDictionary<>
as it does exactly that for youIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With