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");
}
}
}
}
Of course this is a hack... did I just overlook a better way to do this using the standard framework?