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?
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()
.
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.