我试图借助Thread
来计算控制台应用程序中正在运行的线程数:
new Thread(() =>
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}).Start();
之后,我启动了新的Thread
,其中包含非常简单的要执行的逻辑。毫无疑问,线程数增加了1
。对于ThreadPool.QueueUserWorkItem
,它增加了3。
并对Task.Run(() => {...})
做了相同的测试。令人惊讶的是,线程数增加了4
或有时增加了5
。而且很遗憾,我无法理解原因。
这里是完整的测试代码:
static void Main(string[] args)
{
new Thread(() =>
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}).Start();
//Task.Run(() =>
//{
// Thread.Sleep(5000);
//}); // thread count is 12
//new TaskFactory().StartNew(() =>
//{
// Thread.Sleep(5000);
//}); // thread count is 12
//ThreadPool.QueueUserWorkItem((onj) =>
//{
// Thread.Sleep(5000);
//}); // thread count is 9
//new Thread(() =>
//{
// Thread.Sleep(5000);
//}).Start(); // thread count is 7
Console.ReadLine();
}
我的问题是,为什么运行新的Task会使线程数增加4或5?为什么将线程池的工作项目排队,会使线程数增加3?]
已更新:我从动作主体中删除了Thread.Slepp
调用,但是每个示例的线程数都没有改变。
当您通过调用QueueUserItem
或创建Task
将工作排队到线程池中时,线程池将使用默认的初始线程数(通常为四个)进行初始化。