12

Hashtables have a syncroot property but generic dictionaries don't. If I have code that does this:

lock (hashtable.Syncroot)
{
....
}

How do I replicate this if I am removing the hashtable and changing to generic dictionaries?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
leora
  • 188,729
  • 360
  • 878
  • 1,366

4 Answers4

12

If you are going strictly for compatability then Bryan is correct. This is the best way to maintain your current semantics on top of a Dictionary.

Expanding on it though. The reason the SyncRoot property was not directly added to the generic dictionary is that it's a dangerous way to do synchronization. It's only slighly better than "lock(this)" which is very dangerous and prone to deadlocks. Here are a couple of links that speak to why this is bad.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 6
    Completely agree. Yet I really hate it when people answer with "this is bad, don't do it" :). Most of the time people ask a question they are often stuck in a particular scenario and need to work through it. I try to give help on the problem and advice on why it's bad and how to avoid it. – JaredPar Nov 29 '08 at 20:28
7

The new thinking behind SyncRoot is that it was a mistake in the original design. If the only thing to lock is the dictionary and it's private, you can lock it or another object that serves as the synchronization object. The latter technique is useful when the state you are protecting is more than just the dictionary.

// used as you would have used SyncRoot before
object _syncLock = new object();
Dictionary<string, int> numberMapper = new Dictionary<string, int>();

// in some method...
lock (_syncLock)
{
    // use the dictionary here.
}
denis phillips
  • 12,550
  • 5
  • 33
  • 47
  • Do you have a source quote on that it was a mistake in the original design? – dalle Nov 29 '08 at 17:53
  • 1
    Brad Abrams and Krzysztof Cwalina (Program managers of .NET) says so: http://blogs.msdn.com/brada/archive/2003/09/28/50391.aspx – netadictos Nov 29 '08 at 18:14
  • 1
    Jeffrey Richter also covers this error in design in CLR Via C#. –  Nov 29 '08 at 20:07
5
var dictionary = new Dictionary<int, string>();

lock(((ICollection) dictionary).SyncRoot)
{
    // ...
}
Bryan Watts
  • 44,911
  • 16
  • 83
  • 88
3

If the hashtable/dictionary isn't public, you could just lock the dictionary object itself.

Will Dean
  • 39,055
  • 11
  • 90
  • 118