使用Asyc Await从事件更新UI [英] Updating UI from events using asyc await

查看:116
本文介绍了使用Asyc Await从事件更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何在使用异步/等待模式时从事件更新UI. 以下是我在WinForm应用程序上使用的测试代码.我什至不确定这是否是正确的方法.允许pwe_StatusUpdate方法更新UI的必要条件是什么?那里发生了跨线程操作错误.

I am trying to understand how to update a UI from an event while using async/await pattern. Below is the test code I am using on a WinForm app. I am not even sure this is the right way to go about it. What is necessary to allow the pwe_StatusUpdate method to update the UI? The cross-thread operation error is thrown there.

感谢阅读.

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

-

推荐答案

c0>模式支持进度更新.

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

In short, your async method can take an IProgress<T>, and your calling code passes in an implementation of that interface (usually 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));

这篇关于使用Asyc Await从事件更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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