C#BackgroundWorker组件_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C#BackgroundWorker组件

C#BackgroundWorker组件

 2013/11/18 17:22:39  神秘藏宝室~  博客园  我要评论(0)
  • 摘要:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;namespaceProgessBarTest{publicpartialclassForm1:Form
  • 标签:C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

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

        private void button1_Click(object sender, EventArgs e)
        {
            this.btn_Calculate.Enabled = false;//设置计算按键不可用
            this.tb_result.Text = string.Empty;//清空文本框内容
            this.btn_cancel.Enabled = true; //设置取消按键可用
            this.progressBar1.Value = 0;

            //启动后台线程,实例化一个CalcInput对象传给新线程
            backgroundWorker1.RunWorkerAsync(
                                            new CalcInput(
                                                            int.Parse(this.tb_x.Text),
                                                            int.Parse(this.tb_y.Text)
                                                            )
                                            );
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //从DoWorkEventArgs类型参数e的Argument属性得到传入的对象实例
            CalcInput input = (CalcInput)e.Argument;
            //模拟执行时间
            for (int i = 0; i < 10; i++)
            {
                input.x += input.y;
                Thread.Sleep(300);
                if(backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }

            //将计算结果交给参数e的Result属性
            e.Result = input.x;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.btn_Calculate.Enabled = true;//设置计算按键不可用

            if (e.Cancelled)
            {
                this.tb_result.Text = "计算中断";
            }
            else
            {
                this.tb_result.Text = e.Result.ToString();
            }

            this.btn_cancel.Enabled = false; 
            this.progressBar1.Value = 100;

            
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
        }

    }
}

1
发表评论
用户名: 匿名