首页 > 编程开发 > C类语言    日期:2021-07-15 / 浏览

当构建一个图形化的Windows Form桌面应用程序并且需要执行在应用程序主UI线程之外的线程中长时间的任务时,BackgroundWorker类就很有用了。

要使用BackgroundWorker,我们只需要告诉它希望在后台执行那个方法并且调用RunWorkerAsync()即可

c# BackgroundWorker组件的作用

public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      int a = int.Parse(textBox1.Text.Trim());
      int b = int.Parse(textBox2.Text.Trim());
      Add ad = new Add(a,b);
      backgroundWorker1.RunWorkerAsync(ad);
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
       Add args=(Add)e.Argument;
       for (int i = 0; i < 11; i++)
       {
         Thread.Sleep(200);
         backgroundWorker1.ReportProgress(i*10);
       }
      
       e.Result = args.a + args.b;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      label1.Text = e.Result.ToString();
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
      progressBar1.Value = e.ProgressPercentage;
    }
  }
  public class Add
  {
    public int a;
    public int b;
    public Add(int a, int b)
    {
      this.a = a;
      this.b = b;
    }

  }

以上就是c# BackgroundWorker组件的作用的详细内容,更多关于c# BackgroundWorker组件的资料请关注其它相关文章!

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章