Middle · Trace · Semaphore permits are not monitor ownership

Trace the nested zero-timeout wait, restored count, and extra release.

Think through your answer before opening the explanation.

Runtime & concurrency

using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

using var gate = new SemaphoreSlim(1, 1);
await gate.WaitAsync();
bool nested = await gate.WaitAsync(0);
gate.Release();
Console.WriteLine($"nested:{nested}");
Console.WriteLine($"permits:{gate.CurrentCount}");
bool rejected = false;
try { gate.Release(); } catch (SemaphoreFullException) { rejected = true; }
Console.WriteLine($"over-release:{rejected}");
Reveal answer and reasoning

The output is nested:False, permits:1, and over-release:True. The first awaited wait consumes the only permit. The second wait uses a zero timeout and therefore returns false while that permit is held. Releasing the successful first acquisition restores the count to its explicit maximum one. The additional release exceeds that maximum and is caught as SemaphoreFullException.

No monitor recursion rule makes the nested wait succeed just because the same flow called it. A common wrong trace increments the count for the failed acquisition, or assumes the last Release is harmless. This snippet does not create competing OS workers or demonstrate fairness. The external lab separately proves that a different thread can release a permit under an arranged ownership handoff.

That permission belongs to the primitive's contract and still requires application discipline; it is not evidence that any caller may release at any point.

What a strong answer covers

  • The held single permit makes the nested wait false.
  • Only the successful acquisition is released.
  • The configured maximum rejects the extra release.

Common pitfall

Releasing for a failed wait or expecting monitor-style reentrancy from a permit count.

Follow-up questions

  1. What changes if the maximum is omitted?
  2. How would a canceled acquisition affect the release path?

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