backgroundWorker1
Posted xe2011
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了backgroundWorker1相关的知识,希望对你有一定的参考价值。
为了确保 backgroundWorker1_ProgressChanged事件能起作用 设置 WorkerReportsProgress = True;
为了确保能取消操作 设置 WorkerSupportsCancellation = True 这样代码 backgroundWorker1.CancelAsync(); 就不会出错
using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms; namespace WindowsFormsAppBackGroundWorker { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender,EventArgs e) { //start if (!backgroundWorker1.IsBusy) backgroundWorker1.RunWorkerAsync(textBox1.Text);
//此处的Object数值 存放在 DoWorkEventArgs的Argument里面
//可在 backgroundWorker1_DoWork事件的 e.Argument获取
} private void button2_Click(object sender,EventArgs e) { //stop //backgroundWorker1.WorkerSupportsCancellation = true; if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync(); } private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e) { int length = int.Parse(textBox1.Text); progressBar1.Maximum = length; backgroundWorker1.ReportProgress(1,"Begin..."); for (int i = 0; i < length; i++) { if (!backgroundWorker1.CancellationPending) { backgroundWorker1.ReportProgress(i,i); Thread.Sleep(10); } } backgroundWorker1.ReportProgress(100,"Complete!"); } private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e) { progressBar1.Value = unchecked(e.ProgressPercentage); label1.Text = e.UserState.ToString(); } private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) { //Text = "RunWorkerCompleted"; } } }
以上是关于backgroundWorker1的主要内容,如果未能解决你的问题,请参考以下文章