Put in class:
private int entered = 0;
and in the method:
if (Interlocked.Increment(ref entered) != 1) { return; }
Only the first method call can change entered from 0 to 1. Others will do this 2, 3, 4, 5 ...
Obviously, you will need something to reset entered if you want your method to be restored ...
Interlocked.Exchange(ref entered, 0);
at the end of a successful method call.
Ah ... and itโs impossible to use lock / Monitor.* Around await , because the current method thread can change, while almost all synchronization libraries expect that the thread you use to enter the lock is the same as what you use to exit blocking.
You can even use Interlocked.CompareExchange() ...
if (Interlocked.CompareExchange(ref entered, 1, 0) != 0) { return; }
The first input stream will be able to exchange the value entered from 0 to 1, and it will get the old value, 0 (thus, if and failure continues in the remaining code). Other threads will fail CompareExchange and see the "current" value of 1, so type if and exit the method
xanatos
source share