ironhide391
ironhide391

Reputation: 595

How to check whether multiple BackgroundWorkers have compled their task

I have three BackgroundWorkers that each query db for data. I want to how it would be possible to check whether all three BackgroundWorkers have completed their work, so that i can execute some logic ?

This is what i have done so far, but it flags an error saying - The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

public void WaitForThreadsToComplete(Object _Item) 
{
    var results = await Task.WhenAll(
        Task.Run(() => InitiateBackgroundProcessElements(_Item.Id)),
        Task.Run(() => InitiateBackgroundProcessCompulsoryField(_Item.Id)),
        Task.Run(() => InitiateBackgroundProcessFieldRange(_Item.Id)));

    // my logic here
}

Upvotes: 1

Views: 63

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456437

Take another look at your error:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

Then do what the error message says to do:

public async Task WaitForThreadsToCompleteAsync(Object _Item) 
{
  var results = await Task.WhenAll(
    Task.Run(() => InitiateBackgroundProcessElements(_Item.Id)),
    Task.Run(() => InitiateBackgroundProcessCompulsoryField(_Item.Id)),
    Task.Run(() => InitiateBackgroundProcessFieldRange(_Item.Id)));

  // my logic here
}

I also added an Async suffix to your method name so it follows the TAP guidelines.

Upvotes: 2

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You can use RunWorkerCompleted Event to identify this.

Try This:

BackgroundWorker bg1 = new BackgroundWorker();      
bg1.DoWork+=bg1_DoWork;    
bg1.RunWorkerAsync();  //start the worker
bg1.RunWorkerCompleted+=bg1_RunWorkerCompleted;


private void bg1_DoWork(object sender, DoWorkEventArgs e)
{
    /*Worker started - do something*/
}
private void bg1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    /*worker ended - do something*/
}

Upvotes: 0

Related Questions