加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 等待发生的事情 – 异步或同步模型?

发布时间:2020-12-16 01:59:57 所属栏目:百科 来源:网络整理
导读:我有这个方法WaitForReaderArrival,如下所示:(等待读者到达的所有时间运行) public void WaitForReaderArrival() { do { if (ReaderArrived()) { break; } System.Threading.Thread.Sleep(1000); } while (ReaderArrived() == false); } 而我正在等待读者使
我有这个方法WaitForReaderArrival,如下所示:(等待读者到达的所有时间运行)

public void WaitForReaderArrival()
        {
            do
            {
                if (ReaderArrived())
                {
                    break;
                }

                System.Threading.Thread.Sleep(1000);
            } while (ReaderArrived() == false);
        }

而我正在等待读者使用,

await Task.Run(new Action(WaitForReaderArrival));
 if (ReaderArrived())
 {
      //Raise an ReaderArrived here!
    ..//blah blah
 }

我的一位同事让我改变上面这句话

WaitForReaderArrival(); 
 if (ReaderArrived())
 {
    //Raise an ReaderArrived here!
    ..//blah blah
 }

问题是:

>我上面采用的异步模型是不是真的有用?为什么她让我把这条线改为普通的同步方法对我来说仍然是一个问题.
>以上是什么是等待事情发生然后继续的正确方法?

解决方法

Is the asynchronous model that I adopted above is not really useful?
Why she asked me to change that line to normal synchronous methodology
is still a question to me.

您正在使用的代码是the busy waiting loop的略微改进版本,它会对具有限制功能的内容进行轮询.如果您没有任何其他方式获得更改通知,您可以将此循环卸载到池线程,因为您已经在等待Task.Run,??或者更好的是,使用Task.Delay:

public async Task WaitForReaderArrivalAsync()
{
    while (!ReaderArrived())
    {
        await Task.Delay(1000).ConfigureAwait(false);
    }
}

One of my co-worker asked me to change the above line… What in the
above is the right way to wait for something to happen and then
proceed?

你的同事错了.如果你调用原来的WaitForReaderArrival而不用await Task.Run包装它,或者调用上面提出的版本作为WaitForReaderArrivalAsync().Wait(),你将阻止UI线程.要保持UI线程消息循环功能,您应该使代码为“Async All the Way”:

// top-level event handler
async void Button_Click(object sender,EventArgs e)
{
    await WaitForReaderArrivalAsync();
    MessageBox.Show("ReaderArrived!");
}

这是调用它的正确方法.从概念上讲,它与在计时器事件上检查ReaderArrived非常相似,但是async / await为您提供了方便的线性伪同步代码流.

注意,有一种流行的反模式,它忙于等待DoEvents以保持UI响应,有效地在UI线程上创建嵌套的消息循环:

public void WaitForReaderArrival()
{
    while (!ReaderArrived())
    {
        Application.DoEvents();
        System.Threading.Thread.Sleep(100);
    }
}

这样做是错误的:Keeping your UI Responsive and the Dangers of Application.DoEvents.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读