Checking whether the current thread owns a lock

后端 未结 10 651
攒了一身酷
攒了一身酷 2021-02-02 13:32

Suppose I have the following code:

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

    public void SomeMethodA()
    {
        lock         


        
10条回答
  •  孤街浪徒
    2021-02-02 14:10

    There's a fundamental problem with your request. Suppose there were a IsLockHeld() method and you'd use it like this:

    if (not IsLockHeld(someLockObj)) then DoSomething()
    

    This cannot work by design. Your thread could be pre-empted between the if() statement and the method call. Allowing another thread to run and lock the object. Now DoSomething() will run, even though the lock is held.

    The only way to avoid this is to try to take the lock and see if it worked. Monitor.TryEnter().

    You see the exact same pattern at work in Windows. There is no way to check if a file is locked by another process, other than trying to open the file. For the exact same reason.

提交回复
热议问题