开发者

Can multiple threads modify a dictionary?

开发者 https://www.devze.com 2022-12-26 06:10 出处:网络
In C#, 开发者_如何学Pythoncan multiple threads read and write to a Dictionary provided each thread only accesses one element in the dictionary and never accesses another?No, a Dictionary is not Thread

In C#, 开发者_如何学Pythoncan multiple threads read and write to a Dictionary provided each thread only accesses one element in the dictionary and never accesses another?


No, a Dictionary is not Thread-safe.

With the exception of modifying the contents of a reference type (object) that is stored as the Value in a dictionary.

In .NET 4 we will have System.Collections.Concurrent.ConcurrentDictionary.


No, they can't. A dictionary is not thread safe:

A Dictionary(TKey, TValue) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号