c# - 等待某事发生——异步或同步模型?

标签 c# .net multithreading .net-4.5 async-await

我有这个方法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
 }

问题是:

  1. 难道我上面采用的异步模型真的没有用吗?为什么她要求我将该行更改为正常的同步方法,这对我来说仍然是一个问题。

  2. 在上面等待事情发生然后继续的正确方法是什么?

最佳答案

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 的略微改进版本,它正在轮询具有节流功能的内容。 如果您没有任何其他方式获得更改通知,您可以像使用 await 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 .

关于c# - 等待某事发生——异步或同步模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670072/

相关文章:

c# - 从 Jobject Newtonsoft 继承

c# - Entity Framework 6 不在 SQLite 数据库中创建表

c# - 静态构造函数好像没有被调用?

上下文切换执行同一条语句两次

c# - 将变量转换为常量

c# - 以编程方式隐藏重复表

java - JDBC 优化多线程上的 MySql 请求

java - 为什么有人需要线程安全的 SimpleDateFormat 对象?

c# - "GodMode"文件夹内容c#

c# - 使用 QBFC 时的 HRESULT 80040154