不允许异步锁定 [英] Async lock not allowed

查看:102
本文介绍了不允许异步锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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...)

推荐答案

看起来像这样的问题是,线程在获取锁时将阻塞,因此您的方法并不完全异步.要解决此问题,您可以使用 SemaphoreSlim.WaitAsync

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

这篇关于不允许异步锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆