如何锁定对象如何发现? C#

时间:2021-10-27 08:51:17

I have a lock in my code.
I have two threads running at the same time. How can I tell if a thread is locking that object?

我的代码锁定了。我有两个线程同时运行。如何判断线程是否锁定该对象?

private readonly object _lockObject = new Object();

// Both methods running
public void Method1()
{
    if(certainCriteria)
    {
        lock(_lockObject)
        {
        //doWork;
        }
    }
}

// Both methods running
public void Method2()
{
    if( isLocked?(_lockObject))
    {
        //doWork;
    }
}

Has anyone got the isLocked? method?

有没有人得到isLocked?方法?

Thanks in advance!

提前致谢!

1 个解决方案

#1


You could use Monitor.TryEnter (either with a timeout of 0, or the overload which doesn't take a timeout at all) and then immediately call Monitor.Exit if it succeeds - but I'd say this is generally a bad design smell. In particular, the data is stale immediately you return it.

你可以使用Monitor.TryEnter(超时为0,或者根本没有超时的重载)然后立即调用Monitor.Exit如果成功 - 但我会说这通常是一个糟糕的设计气味。特别是,数据在您返回后立即失效。

What are you trying to achieve?

你想要达到什么目的?

#1


You could use Monitor.TryEnter (either with a timeout of 0, or the overload which doesn't take a timeout at all) and then immediately call Monitor.Exit if it succeeds - but I'd say this is generally a bad design smell. In particular, the data is stale immediately you return it.

你可以使用Monitor.TryEnter(超时为0,或者根本没有超时的重载)然后立即调用Monitor.Exit如果成功 - 但我会说这通常是一个糟糕的设计气味。特别是,数据在您返回后立即失效。

What are you trying to achieve?

你想要达到什么目的?