码迷,mamicode.com
首页 > 其他好文 > 详细

BackgroundWorker组件的作用

时间:2015-04-22 21:56:49      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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

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

技术分享

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

    }

 

BackgroundWorker组件的作用

标签:

原文地址:http://www.cnblogs.com/wangzhenghua/p/4448752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!