Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking whether the current thread owns a lock
    text
    copied!<p>Suppose I have the following code:</p> <pre><code>public class SomeClass() { private readonly object _lock = new object(); public void SomeMethodA() { lock (_lock) { SomeHelperMethod(); //do something that requires lock on _lock } } public void SomeMethodB() { lock (_lock) { SomeHelperMethod(); //do something that requires lock on _lock } } private void SomeHelperMethod() { lock (_lock) { //do something that requires lock on _lock } } } </code></pre> <p>Locking inside <code>SomeHelperMethod</code> seems redundant and wasteful, since all callers have already taken a lock. However, simply removing the lock from <code>SomeHelperMethod</code> seems dangerous since we might later refactor the code and forget to lock the <code>_lock</code> object prior to calling <code>SomeHelperMethod</code>.</p> <p>Ideally I could work around this by asserting that the current thread owns a lock on <code>_lock</code> inside <code>SomeHelperMethod</code>:</p> <pre><code>private void SomeHelperMethod() { Debug.Assert(Monitor.HasLock(_lock)); //do something that requires lock on _lock } </code></pre> <p>But there does not appear to be such a method. <code>Monitor.TryEnter</code> does <em>not</em> help because locks are re-entrant. Therefore, if the current thread already owns the lock, <code>TryEnter</code> will still succeed and return <code>true</code>. The only time it will fail is if another thread owns the lock and the call times out.</p> <p>So, does such a method exist? If not, why? It does not seem dangerous at all to me, since it merely tells you whether the current thread (not another thread) owns a lock or not.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload