whats is the easiest way to make C# dictionary access thread safe? Preferably just using lock(object) but any other ideas welcome!
Many common operations on a dict are atomic, meaning that they are thread-safe.
Yes, it's thread safe if you only read it/ use TryGetValue : Documentation: 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.
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
In .NET 4 you have the ConcurrentDictionary class.
If you need to use an older version of .NET, and want to write it yourself:
private object lockObject
lockObject
around every access to the dictionaryIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With