leora
leora

Reputation: 196429

Can you lock on a generic dictionary?

Or should you always create some other lock object?

Upvotes: 6

Views: 7414

Answers (2)

Michael Haren
Michael Haren

Reputation: 108236

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.

Upvotes: 14

Vilx-
Vilx-

Reputation: 106904

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

Upvotes: 1

Related Questions