A semaphore is released outside a finally block, so an exception between wait and release keeps it taken
What it finds
After await gate.WaitAsync(), an exception thrown before gate.Release() leaves the semaphore taken for good, and every later caller waits forever. Releasing in a finally whose try follows the wait guarantees the release. The rule reports Release() on a variable declared as SemaphoreSlim or Semaphore when the same method waits on it and no finally block of the method releases it.
From the rule's source, unprotected_semaphore_release.rs.
using System.Threading;using System.Threading.Tasks; class Gate{ private readonly SemaphoreSlim gate = new SemaphoreSlim(1); async Task Run() { await gate.WaitAsync(); Work(); gate.Release();tx0 reports: the semaphore is released outside finally } async Task Safe() { await gate.WaitAsync(); try { Work(); } finally { gate.Release(); } } void Work() { }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:unprotected-semaphore-release" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:unprotected-semaphore-release] reason="..."tx0 explain tx0/csharp:unprotected-semaphore-release shows the same in the terminal. Found a false positive? Report it.