微软提供的 backgroundWorker 是个非常好的用于异步操作的组件。下面就简单说明一下使用该组件实现异步处理大批量数据并用进度条显示处理进度的功能 , 并提供取消功能。通过在主窗体点击按钮弹出进度条模式窗体,提示用户数据处理进度。效果图如下:
调用代码:
private void button1_Click (object sender , EventArgs e )
{
this .backgroundWorker1 .RunWorkerAsync ();// 运行 backgroundWorker 组件
// 显示进度条窗体
ProcessForm form = new ProcessForm (this .backgroundWorker1 );
form .ShowDialog (this );
form .Close ();
}
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 ();
}