Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Find Out If An Object Is Locked? c#

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?

Thanks in advance!

like image 543
divinci Avatar asked Jun 16 '09 14:06

divinci


1 Answers

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.

What are you trying to achieve?

like image 170
Jon Skeet Avatar answered Oct 31 '22 18:10

Jon Skeet