I wrote a simple synchronization primitive that I can use with async operations on an external REST service so that I don't call it twice from different threads and have one call fail due to not having the latest state. Despite obvious limitations of that design decision I think this should solve my problem...struct DumbAsyncMutex{    int busy;    public async Task WithMutexAsync(Func<Task> t)    {        while (Interlocked.CompareExchange(ref busy, 1, 0) != 0)        {            await Task.Delay(100);        }        try        {            await t();        }        finally        {            while (Interlocked.CompareExchange(ref busy, 0, 1) != 1)            {                throw new Exception(Releasing the mutex failed - but this should never happen);            }        }    }}
Implementing an asynchronous mutex in C#
c#;asynchronous;synchronization
A better alternative to the busy wait loop would be to use a Semaphore - in this case a SemaphoreSlim would probably be the most appropriate. Semaphores are not reentrant. This would simplify the implementation to:struct DumbAsyncMutex{    private SemaphoreSlim _Semaphore = new SemaphoreSlim(1, 1);    public async Task WithMutexAsync(Func<Task> t)    {        await _Semaphore.WaitAsync();        try        {            await t();        }        finally        {            _Semaphore.Release(1);        }    }}The advantage is that it has async support and you can abandon the waiting by using cancellation tokens. 