如何知道循环中的所有工作人员何时完成?以及如何在所有工人之后“执行” bw_RunWorkerCompleted。我尝试了几种方法,但都失败了。主要工人总是先完成。
.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;
}
}
}