【发布时间】:2011-02-22 07:39:02
【问题描述】:
我想了解 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);
}
}
这是否会运行 50 个“任务”,每组 2 个 (int c),直到它们全部完成?或者我不明白它的真正作用。
【问题讨论】:
-
嗯,你试过运行它并观察会发生什么吗?
-
这不是很好地解释了 SetMinThreads 应该做什么。 msdn.microsoft.com/en-us/library/… ...最终,实际启动的线程数将取决于可用的系统资源,每次运行时可能会发生变化。
标签: c# multithreading visual-studio-2010 threadpool