Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with @Leonardo Garcia Crespo's comment. From what I see here, you only write to the dictionary in the static constructor, which will only be called once per app domain. Everything else is a read and the generic dictionary supports multiple readers if the collection isn't modified. The problem could only lie in the code that's being invoked. It also needs to be thread-safe. Alternatively, you could use another dictionary of associated locks and lock the corresponding lock so that you can only call one non-thread-safe instance at a time.</p> <pre><code>public static class MyClass { public static Dictionary&lt;string,SomeDisposableClass&gt; dict = null; public static Dictionary&lt;string,object&gt; locks = null; static MyClass() { // populate the dictionary locks = new Dictionary&lt;string,object&gt;(); foreach (var key in dict.Keys) { locks[key] = new object(); } } public static void UseDictionary( string name ) { var obj = dict[name]; var sync = locks[name]; lock(sync) { obj.DoSomething(); } } } </code></pre> <p>You could also use a Singleton pattern, but if you only have the one static method that's probably not necessary. I will note that this will be horrible to work around for any code that uses this class.</p> <p>And, yes, I know that it will be single threaded if called 1000 times with the same value for <code>name</code>. If the method that's being called isn't thread-safe, though, that's the best you can do. This way, at least, you can have multiple threads operating for different values of <code>name</code> at the same time since they lock on different objects.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload