Basically, I want to make multiple asynchronous requests to a tcp Server. I currently have a working client that is only synchronous and blocks the UI on every network call. Since multiple requests might occur at almost the same time, I tried to do this:
private object readonly readLock = new object();
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
lock (readLock)
{
Details details = await connection.GetDetailsAsync();
detailsListBox.Items = details;
}
}
I am sure this is not a good use of lock but it's the only way I can think of that could make the calls wait for their turn. Is there an object I can use to achieve this kind of behavior? I thought Monitor would be the same so I didn't try (I understand they're multithreading stuff but that's all I'm familiar with...)
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();
}
}