6

Or should you always create some other lock object?

Sam
  • 7,157
  • 15
  • 45
  • 65
leora
  • 177,207
  • 343
  • 852
  • 1,351

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
  • 101,522
  • 39
  • 162
  • 203
  • 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-
  • 101,209
  • 85
  • 267
  • 409