小编典典

不允许异步锁定

c#

基本上,我想向一个TCP服务器发出多个异步请求。我目前有一个工作的客户端,该客户端仅是同步的,并且在每次网络调用时都会阻止UI。由于可能几乎同时发生多个请求,因此我尝试这样做:

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;
    }
}

我确信这不是锁的好用法,但这是我可以想到的唯一方法,可以使呼叫等待轮到他们。有没有可以用来实现这种行为的对象?我以为Monitor是一样的,所以我没有尝试(我知道它们是多线程的东西,但这就是我所熟悉的…)


阅读 404

收藏
2020-05-19

共1个答案

小编典典

看起来您的问题是线程在获取锁时将阻塞,因此您的方法并不完全异步。为了解决这个问题,您可以使用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();
    }
}
2020-05-19