views:

870

answers:

1

Hi there,

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!

+5  A: 

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?

Jon Skeet
@Jon: Yaow is too quick, yaaw is (reads better if you can manage a Black country accent). It was what I was going to suggest with a huge caveat "It works on the basis the we "know" how lock works".
AnthonyWJones
I'm not particularly bothered by the fact that it depends on knowing how lock works - it's not like that's going to change. It's just that it feels plain wrong. I dare say there are *some* situations where it's useful, but probably fewer than the places where it's actually used!
Jon Skeet
Hi again Jon! I am implementing a BufferManager. Basically it has a Stack of Buffers. When a thread pop()s the stack and it is empty - I want all threads to wait on their next pop() while a thread fills up the stack. Once filled - all other threads to keep on poping. I am unsure as to the c# locking mechanisms though!
divinci
I'm not sure why that would require you to conditionally lock. Use Monitor.Wait and Monitor.Pulse/PulseAll and I'd expect you to be okay. Which part of your BufferManager would you want to conditionally lock?
Jon Skeet
So this is a producer-consumer pattern? You have some threads producing items and putting them on a list, and some threads consuming the items, and removing them? If so, this is a well-studied pattern; there's lots of literature on how to properly implement this pattern.
Eric Lippert