c# - 使用异步等待从事件更新 UI

标签 c# asynchronous async-await

我想了解如何在使用异步/等待模式时根据事件更新 UI。 下面是我在 WinForm 应用程序上使用的测试代码。我什至不确定这是正确的方法。允许 pwe_StatusUpdate 方法更新 UI 需要什么?那里抛出跨线程操作错误。

感谢阅读。

 // calling code
    ProcessWithEvents pwe = new ProcessWithEvents();
    pwe.StatusUpdate += pwe_StatusUpdate;
    await pwe.Run();



 void pwe_StatusUpdate(string updateMsg)
    {
      // Error Here: Cross-thread operation not valid: Control '_listBox_Output' accessed from a thread other than the thread it was created on.
      _listBox_Output.Items.Add(updateMsg);
    }

-

// Class with long running process and event    
public delegate void StatusUpdateHandler(string updateMsg);

 public class ProcessWithEvents
  {
    public event StatusUpdateHandler StatusUpdate;

    public async Task Run()
    {
        await Task.Run(() =>
        {
            for (int i = 0; i < 10; i++)
                {

                    RaiseUpdateEvent(String.Format("Update {0}", i));

                    Thread.Sleep(500);
                }
            });

        }

        private void RaiseUpdateEvent(string msg)
        {
        if (StatusUpdate != null)
            StatusUpdate(msg);
        }
   }

-

最佳答案

The async pattern has support for progress updates .

简而言之,您的 async方法可以采用 IProgress<T> ,并且您的调用代码传入该接口(interface)的实现(通常是 Progress<T> )。

public class ProcessWithUpdates
{
  public async Task Run(IProgress<string> progress)
  {
    await Task.Run(() =>
    {
      for (int i = 0; i < 10; i++)
      {
        if (progress != null)
          progress.Report(String.Format("Update {0}", i));
        Thread.Sleep(500);
      }
    });
  }
}

// calling code
ProcessWithUpdates pwp = new ProcessWithUpdates();
await pwp.Run(new Progress<string>(pwp_StatusUpdate));

关于c# - 使用异步等待从事件更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17631275/

相关文章:

c - 如果我在对句柄 h 的异步读取尚未完成之前调用 CloseHandle(h) 怎么办?

c# - 使用 C# 7.0 的新 TaskLike 异步支持是否可以编写 IObservable<T> 生成器

c# - 将 Expression<Func<T,object>> 转换为字符串

c# winforms events 在转义时恢复文本框内容

c# - isArchived 为 false 时的 MongoDB C# 驱动程序唯一索引 PartialFilterExpression

c# - 'context' 在 C# async/await 代码中到底意味着什么?

asynchronous - 在 Meteor.call 回调中对 sys.exec 的 Meteor 回调

c# - WCF REST GET 与 JSON 请求对象?

firebase - 异步函数中的异步操作

c# - 异步调用异步委托(delegate)?