是否有与Java CompletionService等效的C#来对已完成的线程做出反应?

有很多关于如何等待所有“工人”工作完成的例子,但是当每个工人以与Java的CompletionService相同的方式完成时,会做出什么反应呢?

我已经把一些有效的东西砍了,但这看起来很脆弱:

int completedWorkers = 0; while (completedWorkers < workerCount) { int eventId = WaitHandle.WaitAny(eventArray); events[eventId].Reset(); completedWorkers++; Console.WriteLine("Worker {0} has completed. {1} have now completed.", eventId, completedWorkers); } Console.WriteLine("All threads have finished"); 

这依赖于一个ManualResetEvent实例数组(在我的示例中为’eventArray’),类似于Microsoft示例中所示, http://msdn.microsoft.com/en-us/library/3dasc8as.aspx (但是他们的代码使用WaitAll()等待所有工人完成,而不是每个工人完成后做出反应。

编辑:

我已经接受了道格拉斯使用TPL的答案,但作为参考,代表们提供了开箱即用的function:

 IAsyncResult result = caller.BeginInvoke( new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); ... void CallbackMethod(IAsyncResult ar) { // 'react' to async delegates completing } 

如果使用任务并行库,则可以为每个任务附加一个延续。

 int completedWorkers = 0; var continuations = tasks.Select((task, index) => task.ContinueWith(antecedent => { lock (tasks) // only required if you want to avoid races between incrementing and writing { int _index = index; // avoid closures issue completedWorkers++; // if lock is removed, replace with: Interlocked.Increment(ref completedWorkers); Console.WriteLine("Worker {0} has completed. {1} have now completed.", _index, completedWorkers); } })); Task.WaitAll(continuations.ToArray()); Console.WriteLine("All threads have finished"); 

我在这里找到了一个需要.NET 4.5的例子: http : //msdn.microsoft.com/en-us/library/jj155756.aspx

 // ***Add a loop to process the tasks one at a time until none remain. while (downloadTasks.Count > 0) { // Identify the first task that completes. Task firstFinishedTask = await Task.WhenAny(downloadTasks); // ***Remove the selected task from the list so that you don't // process it more than once. downloadTasks.Remove(firstFinishedTask); // Await the completed task. int length = await firstFinishedTask; resultsTextBox.Text += String.Format("\r\nLength of the download: {0}", length); }