检查当前线程是否拥有一个锁 [英] Checking whether the current thread owns a lock

查看:839
本文介绍了检查当前线程是否拥有一个锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下的code:

Suppose I have the following code:

public class SomeClass()
{
    private readonly object _lock = new object();

    public void SomeMethodA()
    {
    	lock (_lock)
    	{
    		SomeHelperMethod();

    		//do something that requires lock on _lock
    	}
    }

    public void SomeMethodB()
    {
    	lock (_lock)
    	{
    		SomeHelperMethod();

    		//do something that requires lock on _lock
    	}
    }

    private void SomeHelperMethod()
    {
    	lock (_lock)
    	{
    		//do something that requires lock on _lock
    	}
    }
}

锁定在 SomeHelperMethod 似乎是多余和浪费,因为所有来电者都已经采取了锁。然而,简单地去除锁定 SomeHelperMethod 似乎危险的,因为我们可能会在以后重构code,却忘了锁 _lock 对象在调用 SomeHelperMethod

Locking inside SomeHelperMethod seems redundant and wasteful, since all callers have already taken a lock. However, simply removing the lock from SomeHelperMethod seems dangerous since we might later refactor the code and forget to lock the _lock object prior to calling SomeHelperMethod.

在理想情况下,我可以解决此通过断言当前线程拥有内部 SomeHelperMethod _lock 锁:

Ideally I could work around this by asserting that the current thread owns a lock on _lock inside SomeHelperMethod:

private void SomeHelperMethod()
{
    Debug.Assert(Monitor.HasLock(_lock));

    //do something that requires lock on _lock
}

但似乎没有成为这样的方法。 Monitor.TryEnter 做的没有的帮助,因为锁是可重入的。因此,如果当前线程已经拥有该锁, TryEnter 仍将成功并返回。它会失败的唯一的一次是,如果另一个线程拥有锁,调用超时。

But there does not appear to be such a method. Monitor.TryEnter does not help because locks are re-entrant. Therefore, if the current thread already owns the lock, TryEnter will still succeed and return true. The only time it will fail is if another thread owns the lock and the call times out.

因此​​,没有这样的方法存在吗?如果不是,为什么?它似乎并不危险,在我的一切,因为它只是告诉你当前线程(而不是另一个线程)是否拥有锁定或没有。

So, does such a method exist? If not, why? It does not seem dangerous at all to me, since it merely tells you whether the current thread (not another thread) owns a lock or not.

推荐答案

这是支持.NET 4.5使用<一个href="http://msdn.microsoft.com/en-US/library/system.threading.monitor.isentered%28v=vs.110%29.aspx">Monitor.IsEntered(object).

This is supported in .NET 4.5 using Monitor.IsEntered(object).

这篇关于检查当前线程是否拥有一个锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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