How to lock a dictionary?

前端 未结 3 1000
情歌与酒
情歌与酒 2021-01-22 03:34

I have a static dictionary in a multi thread application. class A Reads the dictionary and class B Removes from it. I want to lock dictionary when removing from it or reading fr

相关标签:
3条回答
  • 2021-01-22 03:48

    you can use lock

    lock (DicThreads)
    {
       // Any code here is synchronized with other
       // (including this block on other threads)
       // lock(DicThreads) blocks
    }
    

    However, if you have a dictionary of threads in your application, you are probably doing it wrong. Read all about the Task-Based Asynchronous Pattern (TAP) here.

    Stephen Cleary has wirtten a useful AsyncCollection<T> class. Available in the Nito.AsyncEx package on NuGet.

    If you need an asynchronous collection its a good candidate, it actually takes a ConcurrentBag/Stack/Queue or some other IProducerConsumerCollection to provide backing state.

    Remember, as stated, you should not be managing the threads yourself, as illustrated in the question.

    0 讨论(0)
  • 2021-01-22 04:03

    Use a ConcurrentDictionary<T>.

    0 讨论(0)
  • 2021-01-22 04:13

    You could use a ConcurrentDictionary as pwas suggests. If you want to synchronise the dictionary that you have, you use the lock keyword.

    You should generally use a separate object for the synchronising, and don't expose that object outside your scope. That ensures that code outside the block can't use the same object for locks and cause conflicts.

    public static Dictionary<string, Thread> DicThreads = new Dictionary<string, Thread>();
    private static object sync = new Object();
    
    Class A() {
    
      private void MethodA() {
        lock (sync) {
          if (DicThreads.ContainsKey(key)) {
            if (DicThreads[key] == null || DicThreads[key].ThreadState == ThreadState.Stopped) {
              //--- Do something
            }
          }
        }
      }
    
    }
    
    class B {
    
      private void MethodB() {
        lock (sync) {
          DicThreads.Remove(key)
        }
     }
    
    }
    
    0 讨论(0)
提交回复
热议问题