Why is there no Monitor.EnterAsync-like method
I assume that this is not possible - question is why?
It's possible, it just hasn't been done yet.
Currently, the only async-compatible synchronization primitive in the BCL is SemaphoreSlim
, which can act as a semaphore or a simple mutual-exclusion lock.
I have a basic AsyncMonitor
that I wrote, loosely based on Stephen Toub's blog post series. Note that the semantics are slightly different than the BCL Monitor
; in particular, it does not permit recursive locks (for reasons I describe on my blog).
While there is no asynchronous monitor in .NET by default, Stephen Cleary has a great library AsyncEx which deals with synchronization issues when using async/await.
It has an AsyncMonitor
class, which does pretty much exactly what you're looking for. You can get it either from GitHub or as a NuGet package.
Usage example:
var monitor = new AsyncMonitor();
using (await monitor.EnterAsync())
{
// Critical section
}