簡體   English   中英

C#backgroundworker在for循環中啟動

[英]C# backgroundworker started within a for loop

我有以下代碼來啟動后台工作者:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM