views:

106

answers:

2

When using Monitor.Wait(object obj) what should one use for the obj? In this article I'm reading on multithreading in .NET the author instantiates a new Object() to be used only as a monitor lock. Is this what you should do in practice, or is it more typical to Monitor the actual variable shared between two or more threads?

+3  A: 

Yes, I normally lock on a new object created specially for that purpose. I also make sure that it is private and static and not a Type object. It's also important to realize that you're not really "locking" a variable or object, but using the lock as a token that prevents execution of a block of code on multiple threads.

Locking on this (the current instance if you're using C#) is less preferred because any code that has access to the instance could put a lock on it, increasing the chance of a deadlock. By creating your own lock object, you put yourself in complete control.

Here's an informative article on locking that explains the reasoning behind some of this.

Andy West
Why necessarily static ..? you lock all instances that way when you would not need to.
MaLio
An instance-level lock would only prevent code from acquiring the lock in that instance. Code on different threads could then call the same code on multiple instances, possibly causing an invalid state.
Andy West
+2  A: 

It's also not good to lock on string objects because they are sometimes shared across app-domains like Type objects. Doing so could cause unnecessary contention if you had more than one app-domain.

Brandon Cuff