监视器应该等待什么对象?

发布于 2024-08-19 16:20:06 字数 220 浏览 3 评论 0原文

使用 Monitor.Wait(object obj) 时,应该对 obj 使用什么?在这篇文章中,我正在阅读.NET中的多线程,作者实例化了一个新的Object() 仅用作监视器锁。这是您在实践中应该做的,还是监视两个或多个线程之间共享的实际变量更典型?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风轻花落早 2024-08-26 16:20:06

是的,我通常会锁定专门为此目的创建的新对象。我还确保它是私有的和静态的,并且不是类型对象。同样重要的是要认识到,您并不是真正“锁定”变量或对象,而是将锁用作阻止在多个线程上执行代码块的令牌。

不太推荐锁定 this(如果您使用的是 C#,则为当前实例),因为任何有权访问该实例的代码都可能对其进行锁定,从而增加死锁的可能性。通过创建自己的锁对象,您可以完全控制自己。

这是一篇关于锁定的内容丰富的文章,其中解释了其中一些背后的原因。

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.

深海里的那抹蓝 2024-08-26 16:20:06

锁定字符串对象也不好,因为它们有时会在应用程序域之间共享,例如类型对象。如果您有多个应用程序域,这样做可能会导致不必要的争用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文