What are the differences between AsyncEx.AsyncLock and Scott Hanselman's AsyncLock?

386 Views Asked by At

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:

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?

1

There are 1 best solutions below

12
On

AFAIK the AsyncLock component of the AsyncEx library was authored before the introduction of the SemaphoreSlim.WaitAsync API, and the same is also true for Stephen Toub's AsyncLock synchronization primitive. On the contrary Scott Hanselman's AsyncLock 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 the using statement for purposes other than releasing unmanaged resources.

await mutex.WaitAsync();
try
{
    //...
}
finally { mutex.Release(); }

It's not much more code than:

using (await mutex.LockAsync())
{
    //...
}