应该监视器等待什么对象

应该监视器等待什么对象

本文介绍了应该监视器等待什么对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Monitor.Wait(obj对象),应该使用什么样的OBJ?在此文章我读的多线程在.NET中笔者实例化一个新对象()的使用仅作为监视器锁。这是你应该做的实践中,或者是更典型的监视两个或多个线程之间共享的实际变量?

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?

推荐答案

是的,我通常在为该目的而专门设立一个新的对象锁定。我也确保它是私有的,静态的和的没有的Type对象。同样重要的是要认识到你是不是真正的锁定一个变量或对象,但是使用锁作为一个令牌prevents执行多个线程code块。

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.

锁定(当前实例,如果你使用的是C#)小于preferred因为任何code具有访问实例可以把一锁就可以了,增加死锁的机会。通过创建自己的锁对象,你把自己完全控制。

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.

这篇关于应该监视器等待什么对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:54