Senior · Design · Monitor locks are reentrant and thread-owned

How would you protect an operation that must await while preserving explicit acquisition and cleanup ownership?

Think through your answer before opening the explanation.

Runtime & concurrency

Reveal answer and reasoning

Decide whether only a short synchronous state transition needs protection or whether exclusivity must span the asynchronous operation. For the former, keep a private object monitor around that short transition and await outside it. For the latter, choose an async-compatible permit or lease protocol with a documented lifetime instead of carrying thread-owned Monitor entry across an arbitrary continuation.

Track successful acquisition before constructing the release owner, handle cancellation before acquisition without releasing, and keep the underlying synchronization object alive until every lease and waiter is finished. Test normal completion, target failure, canceled acquisition, and repeated cleanup. The wrong design manually calls Monitor.Enter before await and assumes the continuation must run on the original owner because one test happened to do so.

A completed await or a lucky scheduler can hide that defect without changing the primitive's thread-affinity rule.

What a strong answer covers

  • Keep synchronous monitor scopes short where possible.
  • Use an explicit async-compatible owner across suspension.
  • Test cancellation and cleanup without thread-switch assumptions.

Common pitfall

Using a lucky same-thread continuation as justification for Monitor ownership across await.

Follow-up questions

  1. How would repeated disposal avoid over-release?
  2. Does SemaphoreSlim promise FIFO fairness?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions