有没有一种方法可以检测对象是否被锁定? [英] Is there a way to detect if an object is locked?

查看:76
本文介绍了有没有一种方法可以检测对象是否被锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以确定对象是否已在C#中锁定?通过从类内部队列中读取的设计,我处于令人羡慕的位置,并且需要将内容转储到类中的集合中.但是,该集合也可以从类外部的接口读取/写入.因此很明显,有时可能会在我要写入集合的同时写入集合.

Is there any way to determine if an object is locked in C#? I have the unenviable position, through design where I'm reading from a queue inside a class, and I need to dump the contents into a collection in the class. But that collection is also read/write from an interface outside the class. So obviously there may be a case when the collection is being written to, as the same time I want to write to it.

我可以对它进行编程,比如说使用委托,但是这很丑陋.

I could program round it, say using delegate but it would be ugly.

推荐答案

您始终可以调用静态 TryEnter方法 "rel =" noreferrer"> Monitor类,将值0用作等待值.如果已锁定,则呼叫将返回false.

You can always call the static TryEnter method on the Monitor class using a value of 0 for the value to wait. If it is locked, then the call will return false.

但是,这里的问题是,您需要确保尝试同步访问的列表本身已锁定,以便同步访问.

However, the problem here is that you need to make sure that the list that you are trying to synchronize access to is being locked on itself in order to synchronize access.

使用访问同步的对象作为要锁定的对象(暴露了太多的对象内部细节)通常是一种不好的做法.

It's generally bad practice to use the object that access is being synchronized as the object to lock on (exposing too much of the internal details of an object).

请记住,该锁可能在其他任何东西上,因此,除非您确定该列表已被锁定,否则仅在该列表上调用它是没有意义的.

Remember, the lock could be on anything else, so just calling this on that list is pointless unless you are sure that list is what is being locked on.

这篇关于有没有一种方法可以检测对象是否被锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆