微软提供的backgroundWorker是个非常好的用于异步操作的组件。下面就简单说明一下使用该组件实现异步处理大批量数据并用进度条显示处理进度的功能,并提供取消功能。通过在主窗体点击按钮弹出进度条模式窗体,提示用户数据处理进度。效果图如下:
调用代码:
private void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();//运行backgroundWorker组件
//显示进度条窗体
ProcessForm form = new ProcessForm(this.backgroundWorker1);
form.ShowDialog(this);
form.Close();
}
DoWork事件:在此事件中处理大批量数据 RunWorkerCompleted事件:无论是程序正常完成还是用户点击取消按钮,都会触发该事件 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
ProcessForm窗体事件(进度条窗体)
private BackgroundWorker backgroundWorker1;
public ProcessForm(BackgroundWorker backgroundWorker1)
{
InitializeComponent();
this.backgroundWorker1 = backgroundWorker1;
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void cancelButton1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
this.cancelButton1.Enabled = false;
this.Close();
}
完整源码请进入群下载