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
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
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.