Monitor.Enter is called outside a try whose finally calls Monitor.Exit

tx0/csharp:monitor-without-finallyrecommendedwarningreliability/concurrencydepth fastbug

What it finds

When the code between Monitor.Enter and Monitor.Exit throws, the monitor stays held and every other thread that wants it waits forever. lock, or Exit in a finally block, releases it on every path.

From the rule's source, monitor_without_finally.rs.

Example from the rule's tests
using System.Threading; class Gate{    private readonly object sync = new object();     void Bad()    {        Monitor.Enter(sync);tx0 reports: this monitor is not released in a finally block        Work();        Monitor.Exit(sync);    }     void Good()    {        Monitor.Enter(sync);        try        {            Work();        }        finally        {            Monitor.Exit(sync);        }    }     void Work() { }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

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:

tx0.toml
[rules]
"tx0/csharp:monitor-without-finally" = "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:monitor-without-finally] reason="..."

tx0 explain tx0/csharp:monitor-without-finally shows the same in the terminal. Found a false positive? Report it.