问题
If I have a
Dictionary<int, StreamReader> myDic = new Dictionary<int, StreamReader>
//Populate dictionary
One thread does
myDic[0] = new StreamReader(path);
Another thread does
myDic[1] = new StreamReader(otherpath)
Is this thread safe because the actual item in the dictionary getting modified is different to the one on the other thread or will I get a InvalidOperationException: Collection was modified
回答1:
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.
回答2:
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. *
回答3:
To improve your code, you might want to look up the ConcurrentDictionary class. It will solve some problems with multi-threading.
来源:https://stackoverflow.com/questions/8182945/thread-safety-with-dictionary