26

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

Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
Tom
  • 311
  • 1
  • 5
  • 7

1 Answers1

58

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
Henk Holterman
  • 250,905
  • 30
  • 306
  • 490
  • 2
    Just wonder, why "use a seperate lock object"? – MFatihMAR Jul 24 '15 at 16:46
  • 7
    @MonoLightTech - a bit theoretical, but if code inside the Dictionary class itself or external code that needs to 'see' the collection also locks on it, you might have a deadlock. Use separation of concerns: the lockObject is for locking only. – Henk Holterman Jul 24 '15 at 21:06