Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making dictionary access thread-safe? [duplicate]

Tags:

whats is the easiest way to make C# dictionary access thread safe? Preferably just using lock(object) but any other ideas welcome!

like image 515
Tom Avatar asked May 30 '10 20:05

Tom


People also ask

Are Dict threads safe?

Many common operations on a dict are atomic, meaning that they are thread-safe.

Is Dictionary TryGetValue 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.

What is meaning of thread-safe in Python?

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.


1 Answers

In .NET 4 you have the ConcurrentDictionary class.

If you need to use an older version of .NET, and want to write it yourself:

  • wrap a Dictionary as a private field in your class
  • use a separate private object lockObject
  • take a lock on that lockObject around every access to the dictionary
like image 101
Henk Holterman Avatar answered Feb 17 '23 02:02

Henk Holterman