1

I have the following code to start a background worker:

foreach (var item in this.lstbxItems.Items)
{
    if (!bw.IsBusy)
        bw.RunWorkerAsync(item);
}

Is there a way to wait for the background worker (bw) to finish and then send to it the next item in the list?

Quality Catalyst
  • 6,152
  • 7
  • 35
  • 60
rena
  • 1,111
  • 2
  • 16
  • 29
  • 3
    Which version of .net framework you use? If 4.0 or greater, throw away Backgroundworker and use `Task`. – Sriram Sakthivel Mar 20 '16 at 19:14
  • 1
    I recommend using [TPL then](http://stackoverflow.com/questions/3513432/task-parallel-library-replacement-for-backgroundworker) which will make many of tasks easier. Like waiting for the operation to complete, start multiple tasks concurrently, error handling etc. – Sriram Sakthivel Mar 20 '16 at 19:23
  • This sounds like a perfect situation for using Microsoft's Reactive Extensions (NuGet "Rx-WinForms"). – Enigmativity Mar 20 '16 at 23:33

1 Answers1

0

This sounds like a perfect situation for using Microsoft's Reactive Extensions (NuGet "Rx-WinForms").

Your code would look something like this:

var query =
    from item in this.lstbxItems.Items.ToObservable()
    from result in Observable.Start(() => ProcessItem(item))
    select new { item, result };

IDisposable subscription =
    query
        .ObserveOn(this) /* marshals to UI-thread */
        .Subscribe(x =>
        {
            /* do something with each `x.item` & `x.result`
            as soon as they are asyncronously computed */
        });

If you needed to stop the computation before it completes naturally you can just call subscription.Dispose().

Enigmativity
  • 105,241
  • 11
  • 83
  • 163