dotnet / roslyn-analyzers

MIT License
1.58k stars 465 forks source link

CA1849 reports zero length timeouts as blocking (eg. SemaphoreSlim.Wait(0)) #7271

Closed fowl2 closed 4 months ago

fowl2 commented 6 months ago

Analyzer

Diagnostic ID: CA1849: Call async methods when in an async method

Analyzer source

NuGet Package: Microsoft.CodeAnalysis.NetAnalyzers

Version: 8.0.0, 9.0.0-preview.24122.1

Describe the bug

SemaphoreSlim.Wait will not block if 0 (or TimeSpan.Zero) is passed as the timeout:

millisecondsTimeout: The number of milliseconds to wait, System.Threading.Timeout.Infinite(-1) to wait indefinitely, or zero to test the state of the wait handle and return immediately.

Therefore this rule is a false positive in this case.

Steps To Reproduce

using System.Threading;
using System.Threading.Tasks;

static async Task Main()
{
    using SemaphoreSlim s = new(0);
    s.Wait(0);
}

Expected behavior

No warning.

Actual behavior

CA1849 'SemaphoreSlim.Wait(int)' synchronously blocks. Await 'SemaphoreSlim.WaitAsync()' instead.