Async lock not allowed
Looks like the problem that you have is that threads will block while acquiring the lock, so your method is not completely async. To solve this you can use SemaphoreSlim.WaitAsync
private readonly SemaphoreSlim readLock = new SemaphoreSlim(1, 1);
public async Task UpdateDetailsAsync()
{
//I want every request to wait their turn before requesting (using the connection)
//to prevent a read call from catching any data from another request
await readLock.WaitAsync();
try
{
Details details = await connection.GetDetailsAsync();
detailsListBox.Items = details;
}
finally
{
readLock.Release();
}
}
This problem has been neatly solved by the NuGet package Nito.AsyncEx
which has over 50,000 downloads as of August 2015.
From ReadMe:
#AsyncEx A helper library for async/await.#
Supports .NET 4.5/4.0, iOS, Android, Windows Store 8.0, Windows Phone Silverlight 8.0/7.5, Windows Phone Applications 8.1, Silverlight 5.0/4.0, and all portable libraries thereof.
[snip]
#AsyncLock#
A lot of developers start using this library for AsyncLock, an async-compatible mutual exclusion mechanism. Using AsyncLock is straightforward:
private readonly AsyncLock _mutex = new AsyncLock();
public async Task UseLockAsync()
{
// AsyncLock can be locked asynchronously
using (await _mutex.LockAsync())
{
// It's safe to await while the lock is held
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
See the C# source code on GitHub or install the NuGet package Nito.AsyncEx
.