Returns c# the dictionary in a multithreaded environment

I have announced a dictionary of dictionaries:

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

I have a getter to get the dictionary of a specific index:

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

As you can see, I am working in a multithreaded environment My problem is that I need to return a copy of my dictionary for thread safety like this:

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

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

Cheers!

Thierry

Solution

If you really need to return the dictionary itself, you will need rules on how the thread locks it (fragile, if there is a case without?), Use it in read-only mode (the dictionary is thread safe for read-only, but please note that this assumes that the private code of this class is no longer written to it), use thread safe Dictionary (concurrentdictionary uses stripe locking, my threadsafedictionary uses no lock method, and there are different scenarios, one defeats the other), or make copies according to your suggestions

Or, if you expose a method to retrieve or set the final string found by the two keys, enumerate the secondary keys found by the key, and so on, Then you can not only control the locking completed by a key, but it has other advantages in interface cleaning and releasing the implementation from the interface (for example, you can move from lock based to thread safe dictionary, or vice versa without affecting the calling code)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>