我正在努力理解ThreadPool的作用,这是一个.NET示例:
class Program
{
static void Main()
{
int c = 2;
// Use AutoResetEvent for thread management
AutoResetEvent[] arr = new AutoResetEvent[50];
for (int i = 0; i < arr.Length; ++i)
{
arr[i] = new AutoResetEvent(false);
}
// Set the number of minimum threads
ThreadPool.SetMinThreads(c, 4);
// Enqueue 50 work items that run the code in this delegate function
for (int i = 0; i < arr.Length; i++)
{
ThreadPool.QueueUserWorkItem(delegate(object o)
{
Thread.Sleep(100);
arr[(int)o].Set(); // Signals completion
}, i);
}
// Wait for all tasks to complete
WaitHandle.WaitAll(arr);
}
}
这个程序会以每组2个(int c
)的方式运行50个“任务”,直到它们全部完成吗?还是我没有真正理解它的作用。