Checking whether the current thread owns a lock

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

    Not the best thing to do but ...

    bool OwnsLock(object someLockObj)
    {
      if (Monitor.TryEnter(someLockObj))
      {
        Monitor.Exit();
        return false;
      }
      return true;
    }
    
    Debug.Assert(OwnsLock(_someLockObject), "_someLockObject should be locked when this method is called")
    

提交回复
热议问题