An awaitable semaphore class for the .NET's TPL library which can be used similar to the conventionallock
block.
Thelock
block is mimicked by theusing(await ...)
construct, so you can await entering the critical section in your asynchronous method.
Under the hood there areSemaphoreSlim
instances are being used for synchronization, which is wrapped in a disposable class,see and build the source code with the given Visual Studio 2015 solution. The tests are using Moq and MSPEC.
You can create manyAsyncLock
instances if needed:
privateAsyncLockLock=newAsyncLock();vartoken=newobject();using(awaitLock.AcquireAsync(token)){// critical section}
Or use the singleton version across your application:
using(awaitAsyncLock.CreateAsync(token)){// critical section}
You can also use the synchronous version of both examples - without the 'Async' postfixes.