问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/2186616/what-object-should-a-monitor-wait-on