Windows窗体的BackgroundWorker替代品 [英] BackgroundWorker alternatives for Windows Forms

查看:45
本文介绍了Windows窗体的BackgroundWorker替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Windows Forms应用程序中执行类似的操作?

Is it possible to do something like this in a Windows Forms app?

我试图找到其他更新UI的方法,而不是一直使用BackgroundWorker.也许是这样的吗?:

I'm trying to find other ways of updating the UI instead of using the BackgroundWorker all the time. Maybe something like this?:

public List<String> results = new List<String>();

private void button1_Click(object sender, EventArgs e)
{
    When(SomeLongRunningMethod("get") == true)
    {
        // LongRunningMethod has completed.
        // display results on Form.
        foreach(string result in results)
        {
            this.Controls.Add(new Label() { Text = result; Location = new Point(5, (5 * DateTime.Now.Millisecond)); });
        }
    }
}

public void SomeLongRunningMethod(string value)
{
    if(value == "get")
    {
        // Do work.
        results.Add("blah");
    }
}

上面的内容基本上是这样说的:执行此操作,完成后,将结果添加到表单中."

The above basically says, "Do this and when you're done, add the results to the form."

推荐答案

我建议您将 async / await Task.Run 一起使用.请注意,返回结果更简洁:

I recommend you use async/await with Task.Run. Note that returning the results is cleaner:

private void button1_Click(object sender, EventArgs e)
{
  var results = await Task.Run(() => SomeLongRunningMethod("get"));
  foreach(string result in results)
  {
    this.Controls.Add(new Label() { Text = result; Location = new Point(5, (5 * DateTime.Now.Millisecond)); });
  }
}

public List<string> SomeLongRunningMethod(string value)
{
  var results = new List<string>();
  if(value == "get")
  {
    // Do work.
    results.Add("blah");
  }
  return results;
}

我的博客上有一系列博客文章,描述了 Task.Run 代替 BackgroundWorker .

I have a series of blog posts on my blog that describe how Task.Run acts as a replacement for BackgroundWorker.

这篇关于Windows窗体的BackgroundWorker替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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