检查当前线程是否拥有一个锁线程

2023-09-03 09:34:14 作者:闹到最后我还是比不上她

假设我有以下的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使用Monitor.IsEntered(object).

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