What object should a Monitor wait on?

浪子不回头ぞ 提交于 2019-12-11 02:43:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!