I recently had the need to add an asynchronous variant of the lock
keyword to one of my applications. There are many implementations to choose from, but the two that most appealed to me were:
- AsyncLock from the AsyncEx library.
Main reason: It's from a widely used library. - Scott Hanselman's AsyncLock which is based on Stephen Toub's AsyncLock
Main reason: It's very simple and I can just paste it into my project without needing a new library.
What are the differences during runtime for the two solutions?
Of course the AsyncEx AsyncLock has more features, but assuming I don't need those, how do the two compare?
AFAIK the
AsyncLock
component of the AsyncEx library was authored before the introduction of theSemaphoreSlim.WaitAsync
API, and the same is also true for Stephen Toub'sAsyncLock
synchronization primitive. On the contrary Scott Hanselman'sAsyncLock
was published after the release of the .NET Framework 4.5 (October 2012), and so it is making use of the aforementioned API. It is actually a very thin and lightweight wrapper around this API.My assumption is that all these components have the same runtime behavior. It is hard to say it with absolute confidence for the AsyncEx version, because the source code is quite complex, and it's not contained in a single code file.
My personal preference between those options would be to use none. I find using a
SemaphoreSlim(1, 1)
directly quite convenient, and I am not a fan of (ab)using theusing
statement for purposes other than releasing unmanaged resources.It's not much more code than: