如何知道迴路中的所有工人何時完成?以及如何在所有工作人員之後「執行」bw_RunWorkerCompleted。 我嘗試了幾種方法,但我失敗了。主要工作人員總是先完成。Multi-BackgroundWorker
的.Net 3.5
using System;
using System.ComponentModel;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.RunWorkerAsync();
Console.ReadLine();
}
static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("All");
}
static void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++)
{
BackgroundWorker inBW = new BackgroundWorker();
inBW.DoWork += new DoWorkEventHandler(inBW_DoWork);
inBW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(inBW_RunWorkerCompleted);
inBW.RunWorkerAsync(i.ToString());
}
}
static void inBW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine(e.Result as String);
}
static void inBW_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(new Random().Next(1000, 5000));
e.Result = e.Argument as string;
}
}
}
從異步操作中啓動異步操作對我來說似乎毫無意義。畢竟,對我來說,進行異步操作的唯一/主要原因是保持UI的響應。 –
在這種情況下,.Net Framework V4可以在Task類的幫助下幫助很大。你可以移動到這個版本或更高版本? –
是的,這是因爲UI –