C#BackgroundWorker组件
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(); } } }
文章对您有帮助,开心可以打赏我,金额随意,欢迎来赏!
需要电子方面开发板/传感器/模块等硬件可以到我的淘宝店逛逛