C#下Backgroundworker使用例子
来源:互联网 发布:淘宝宝贝上架时间 编辑:程序博客网 时间:2024/05/17 05:57
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;namespace Backgroundworker使用{ public partial class Form1 : Form { public Form1() { InitializeComponent(); backgroundWorker1.WorkerReportsProgress = true; backgroundWorker1.WorkerSupportsCancellation = true; btn_Stop.Enabled = false; } private void btn_Start_Click(object sender, EventArgs e) { txt_Text.Text = "开始产生10000以内的随机数……\n\n"; btn_Start.Enabled = false; btn_Stop.Enabled = true; //在后台线程开始操作 backgroundWorker1.RunWorkerAsync(); } private void btn_Stop_Click(object sender, EventArgs e) { backgroundWorker1.CancelAsync(); btn_Stop.Enabled = false; btn_Start.Enabled = true; } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //不要直接使用组件实例名称(backgroundWorker1),因为有多个BackgroundWorker时, //直接使用会产生耦合问题,应该通过下面的转换使用它 BackgroundWorker worker = sender as BackgroundWorker; //下面的内容相当于线程要处理的内容。//注意:不要在此事件中和界面控件打交道 Random r = new Random(); int numCount = 0; while (worker.CancellationPending == false) { int num = r.Next(0, 10000); if (num % 5 == 0) { numCount++; worker.ReportProgress(0, num); Thread.Sleep(10); } } e.Result = numCount; } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { int num = (int)e.UserState; txt_Text.Text += num + " \r\n"; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error == null) txt_Text.Text += "\n\n操作停止,共生产" + e.Result + "个能被5整除的随机数"; else txt_Text.Text += "\n操作过程中产生错误:" + e.Error; } }}