6

Or should you always create some other lock object?

Sam
  • 7,252
  • 16
  • 46
  • 65
leora
  • 188,729
  • 360
  • 878
  • 1,366

2 Answers2

14

Yes, cast it to an IDictionary and lock on .SyncRoot:

Generic.Dictionary<int, int> dic = new Generic.Dictionary<int, int>();

lock (((IDictionary)dic).SyncRoot)
{
    // code
}

Thanks to this source for the info.

Of course a thread-safe dictionary would be nice, too, as others have suggested.

Michael Haren
  • 105,752
  • 40
  • 168
  • 205
  • This answer was Accepted, but anyone who read this should also take a look on this for example : http://stackoverflow.com/questions/327654/hashtable-to-dictionary-syncroot . SyncRoot is not the best way to lock on collections. – AFract Jan 15 '14 at 15:06
  • I realize this answer is old. Just wanted to tell you the link is dead now. – Morten Jensen Jun 11 '15 at 13:49
  • Its better to not use "SyncRoot", it was a design problem by .net team, use Lock(_lockObject) instead. – Baloo0ch Feb 19 '18 at 08:48
1

You can lock on any object that you wish (except value-types). It's recommended though to lock on the .SyncRoot object.

Vilx-
  • 104,512
  • 87
  • 279
  • 422