在表单应用程序中多次运行或启动后台工作程序

时间:2012-08-28 12:40:32

标签: c# backgroundworker

我想在完成后再次运行我的后台工作程序.. 那就像

backgroundWorker1.do工作 然后 后台工作者完成 然后运行后台worker1.do再次工作...... 怎么做.. 请注意,我必须一次又一次地运行许多后台工作者.... 谢谢

3 个答案:

答案 0 :(得分:1)

您可以在RunWorkerAsync()事件处理程序

中添加对RunWorkerCompleted的调用
    bw.RunWorkerCompleted += bw_RunWorkerCompleted;

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        ((BackgroundWorker)sender).RunWorkerAsync();
    }

答案 1 :(得分:0)

也许您可以使用相同的属性创建一个新的Backgroundworker,或者只需在完成后调用backgroundworker1.doWork()。

答案 2 :(得分:0)

如果您使用的是.NET 4.0或.NET 4.5,则可以使用Tasks代替BackgroundWorker:

// Here your long running operation
private int LongRunningOperation()
{
   Thread.Sleep(1000);
   return 42;
}

// This operation will be called for processing tasks results
private void ProcessTaskResults(Task t)
{
   // We'll call this method in UI thread, so Invoke/BeginInvoke
   // is not required
   this.textBox.Text = t.Result;

}

// Starting long running operation
private void StartAsyncOperation()
{
   // Starting long running operation using Task.Factory
   // instead of background worker.
   var task = Task.Factory.StartNew(LongRunningOperation);   

   // Subscribing to tasks continuation that calls
   // when our long running operation finished
   task.ContinueWith(t =>
   {
      ProcessTaskResults(t);
      StartOperation();
   // Marking to execute this continuation in the UI thread!
   }, TaskScheduler.FromSynchronizationContext);
}

// somewhere inside you form's code, like btn_Click:
StartAsyncOperation();

基于任务的异步是处理长时间运行操作的更好方法。