C#backgroundworker在for循环中启动

C#backgroundworker在for循环中启动,c#,multithreading,winforms,C#,Multithreading,Winforms,我有以下代码来启动后台工作程序: foreach (var item in this.lstbxItems.Items) { if (!bw.IsBusy) bw.RunWorkerAsync(item); } 是否有一种方法可以等待后台工作程序(bw)完成,然后将列表中的下一项发送给它?这听起来是使用Microsoft的反应式扩展(NuGet“Rx WinForms”)的理想情况 您的代码如下所示: var query = from item in this.

我有以下代码来启动后台工作程序:

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

是否有一种方法可以等待后台工作程序(
bw
)完成,然后将列表中的下一项发送给它?

这听起来是使用Microsoft的反应式扩展(NuGet“Rx WinForms”)的理想情况

您的代码如下所示:

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 */
        });

如果您需要在计算自然完成之前停止计算,您只需调用
subscription.Dispose()

这听起来是使用Microsoft的反应式扩展(NuGet“Rx WinForms”)的理想情况

您的代码如下所示:

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 */
        });

如果需要在计算自然完成之前停止计算,可以调用
subscription.Dispose()

使用哪个版本的.net framework?如果是4.0或更高版本,请抛弃Backgroundworker并使用
任务
。我建议使用它,这将使许多任务变得更简单。如等待操作完成、同时启动多个任务、错误处理等。这听起来是使用Microsoft的反应式扩展(NuGet“Rx WinForms”)的理想情况。您使用的是哪个版本的.net framework?如果是4.0或更高版本,请抛弃Backgroundworker并使用
任务
。我建议使用它,这将使许多任务变得更简单。像等待操作完成、同时启动多个任务、错误处理等。这听起来像是使用Microsoft的反应式扩展(NuGet“Rx WinForms”)的完美情况。