如果您的要求僅僅是阻塞,直到所有的線程完成,那真的很容易 - 只需啓動新線程,然後調用Thread.Join
他們每個人:
using System;
using System.Collections.Generic;
using System.Threading;
public class Test
{
static void Main()
{
var threads = new List<Thread>();
for (int i = 0; i < 10; i++)
{
int copy = i;
Thread thread = new Thread(() => DoWork(copy));
thread.Start();
threads.Add(thread);
}
Console.WriteLine("Main thread blocking");
foreach (Thread thread in threads)
{
thread.Join();
}
Console.WriteLine("Main thread finished");
}
static void DoWork(int thread)
{
Console.WriteLine("Thread {0} doing work", thread);
Random rng = new Random(thread); // Seed with unique numbers
Thread.Sleep(rng.Next(2000));
Console.WriteLine("Thread {0} done", thread);
}
}
編輯:如果你有機會獲得。 NET 4.0,那麼TPL絕對是正確的選擇。否則,我會建議使用生產者/消費者隊列(有大量的示例代碼)。基本上你有一個工作項目隊列,並且有多少個核心線程(假設它們是CPU限制的;你想要根據你的工作量來調整它)。每個消費者線程將從隊列中取出項目並逐個處理它們。具體如何管理這取決於你的情況,但並不複雜。如果您能夠提出開始所需的所有工作,則更容易,以便線程在發現隊列爲空時可以退出。
雖然它可能不會幫你解決這個問題,.NET Framework 4中的新並行編程功能,你可能會感興趣。有些東西要留意 - 它很快就會發布。 http://msdn.microsoft.com/en-us/concurrency/default.aspx – 2010-02-03 23:15:49