If I have a
Dictionary myDic = new Dictionary
//Populate dictionary
One thread does
You will only get InvalidOperationException: Collection was modified
if you enumerate the dictionary while modifying.
However, that is not thread-safe.
If one of those operations causes the dictionary to resize, the other one may get lost.
Instead, use ConcurrentDictionary
.
To improve your code, you might want to look up the ConcurrentDictionary
class. It will solve some problems with multi-threading.
System.Collections.Generic collections are only thread safe if you are reading from multiple threads.
Quoting from MSDN
System.Collections.Generic collection classes do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently
If you want want thread safety for both read and write operations consider using System.Collections.Concurrent
*When you write new code, use the concurrent collection classes whenever the collection will be writing to multiple threads concurrently. *