System.ComponentModel.BackgroundWorker在WinForm中的异步使用

时间:2022-08-15 16:08:42

为了防止操作过程中界面卡死,和WinForm搭配最适合的就是BackgroundWorker了。BackgroundWorker 类

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms; namespace ProcessImpactID
{
public partial class Form1 : Form
{
BackgroundWorker worker = new BackgroundWorker(); public Form1()
{
InitializeComponent(); worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += Worker_ProgressChanged;
//set it to true for support cancel event
//when call CancelAsync() it can set property CancellationPending to true.
worker.WorkerSupportsCancellation = true;
//set it to true for raise Progress Report.
worker.WorkerReportsProgress = true;
} private void btnStart_Click(object sender, EventArgs e)
{
if (worker.IsBusy)
{
MessageBox.Show("the process has been started");
return;
}
worker.RunWorkerAsync("e.argument");
} private void btnStop_Click(object sender, EventArgs e)
{
if (worker.IsBusy)
{
worker.CancelAsync();
}
} private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//this is UI Thread
this.label1.Text = e.ProgressPercentage.ToString();
} void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//bool isThreadPoolThread = System.Threading.Thread.CurrentThread.IsThreadPoolThread;
//this is UI Thread
if (e.Error != null)
{
MessageBox.Show(e.Error.Message, "Error");
return;
}
if (e.Cancelled)
{
MessageBox.Show("the process has been cancelled");
return;
}
MessageBox.Show(e.Result.ToString());
} void worker_DoWork(object sender, DoWorkEventArgs e)
{
//bool isThreadPoolThread = System.Threading.Thread.CurrentThread.IsThreadPoolThread;
string str = (string)e.Argument;
string result = "work result";
worker.ReportProgress(0);
for (int i = 0; i < 100; i++)
{
//if CancellationPending is true, stop process.
//and report process result.
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
Thread.Sleep(1000);
//Report Progress
worker.ReportProgress(i * 1);
} //set the RunWorkerCompleted result
e.Result = string.Format("{0} => {1}", str, result);
}
}
}