FP S6966 "Await WaitAsync Instead" : should not apply rule when inside lock

C# / .NET Rule S6966 “Await WaitAsync Instead” recommends a quick fix that produces a compiler error by trying to await inside a lock.

Using nuget package:

dotnet add package SonarAnalyzer.CSharp --version 10.10.0.116381

And this code:

namespace SmTest
{
    public class TestClass : IDisposable
    {
        private readonly object locktarget;
        private readonly SemaphoreSlim sm;

        public TestClass()
        {
            this.locktarget = new object();
            this.sm = new SemaphoreSlim(1, 1);
        }

        public async Task DoWorkAsync(CancellationToken cancellationToken)
        {

            await Task.Delay(100, cancellationToken);

            lock (this.locktarget)
            {
                Console.WriteLine("Entering semaphore");
                this.sm.Wait();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            this.sm.Dispose();
        }
    }
}

Produces warning:

    D:\source\SonarLintFp\TestClass.cs(22,17): warning S6966: Await WaitAsync instead. (https://rules.sonarsource.com/csharp/RSPEC-6966)

Applying the quick fix produces code that won’t compile:

    D:\source\SonarLintFp\TestClass.cs(24,17): error CS1996: Cannot await in the body of a lock statement

Hi @rcocks-hl,
Thanks for the report!
I agree this is a FP, have added a ticket to our backlog, and have added a reproducer to our code base.

1 Like