Checking whether the current thread owns a lock

后端 未结 10 645
攒了一身酷
攒了一身酷 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:08

    I had similiar requirements of checking whether a lock is locked by the current thread, so I can do something like this.

    public void Method1()
    {
        if(!lockHeld()) lock();
        //DO something
    }
    public void Method2()
    {
        if(!lockHeld()) lock();
        //DO something
    }
    public void Method3()
    {
        if(!lockHeld()) lock();
    
        //Do something
    
        unlock()
    }
    

    So I wrote myself a class for that:

    public class LockObject
    {
        private Object internalLock;
    
        private bool isLocked;
        public bool IsLocked
        {
            get { lock (internalLock) return isLocked; }
            private set { lock (internalLock) isLocked = value; }
        }
    
        public LockObject()
        {
            internalLock = new object();
        }
    
        public void UsingLock(Action method)
        {
            try
            {
                Monitor.Enter(this);
                this.IsLocked = true;
    
                method();
            }
            finally
            {
                this.IsLocked = false;
                Monitor.Exit(this);
            }
        }
    }
    

    Then I can use it as:

        public void Example()
        {
            var obj = new LockObject();
    
            obj.UsingLock(() =>
            {
                //Locked, and obj.IsLocked = true
            });
        }
    

    Note: I ommitted the Lock() Unlock() Methods on this class, but pretty much just wrappers to Monitor.Enter/Exit that set IsLocked to true. The example just illustrates that its very similar to lock(){ } in terms on style.

    Might be unnecessary, but this is useful for me.

提交回复
热议问题