简体   繁体   中英

Run or start background worker more than one time in a form application

I want to run my background worker again when it is complete.. That's like

backgroundWorker1.do work then background worker complete then run background worker1.do work again... How to do it.. Note that I have to run many background worker again and again.... Thank you

You could add a call to RunWorkerAsync() in the RunWorkerCompleted event handler

    bw.RunWorkerCompleted += bw_RunWorkerCompleted;

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

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

If your're using .NET 4.0 or .NET 4.5 you can use Tasks instead of 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();

Task-based asynchrony is a better way when dealing with long running operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM