I need to ensure a method is executed only by one thread at a time. Contrary to what most of the synchronization primitives do, I don't need other threads to wait, I want them to return from the method immediately if it is already executed by another thread. Additional complexity is that the method uses async/await calls.I implemented it using Interlocked.Increment. I tested in a simple test scenario and it seems to be working. However, I'm not sure, is it a correct implementation and will it work in all cases? Or maybe there is a simpler way to achieve the same goal?private int _threadsCount = 0;public async Task Method(){    if (Interlocked.Increment(ref _threadsCount) > 1)    {        Interlocked.Decrement(ref _threadsCount);        return;    }    try    {        await DoWork();    }    finally    {        Interlocked.Decrement(ref _threadsCount);    }}
Make all additional threads return from a method using Interlocked.Increment
c#;multithreading;thread safety
Yes, your code should work. Though the first part can be simplified to:if (Interlocked.CompareExchange(ref _threadsCount, 1, 0) != 0){    return;}