本人初学线程和进程,写了个代码测试window下一个进程能创建多少个线程,但是运行出来看似是个死循环。求助
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace Count
{
class Program
{ // 线程函数
static public void ThreadProc(object obj)
{ // 输出线程的名称与线程ID
Console.WriteLine("线程名称: {0}; 线程ID:{1}. ",
Thread.CurrentThread.Name, AppDomain.GetCurrentThreadId());
// 休眠10s
Thread.Sleep(10);
}
static void Main(string[] args)
{
int countOfThread = 1000000; for (int i = 0; i < countOfThread; ++i)
{
try
{
Thread t = new Thread(ThreadProc);
t.IsBackground = true; // 设置为后台线程
t.Name = "线程" + i.ToString(); // 线程名称
t.Start(); // 启动线程
}
catch (System.Exception e)s
{
Console.WriteLine("线程{0}创建失败,已经到达线程的最大数目{1}.", i, i - 1);
break;
}
} Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace Count
{
class Program
{ // 线程函数
static public void ThreadProc(object obj)
{ // 输出线程的名称与线程ID
Console.WriteLine("线程名称: {0}; 线程ID:{1}. ",
Thread.CurrentThread.Name, AppDomain.GetCurrentThreadId());
// 休眠10s
Thread.Sleep(10);
}
static void Main(string[] args)
{
int countOfThread = 1000000; for (int i = 0; i < countOfThread; ++i)
{
try
{
Thread t = new Thread(ThreadProc);
t.IsBackground = true; // 设置为后台线程
t.Name = "线程" + i.ToString(); // 线程名称
t.Start(); // 启动线程
}
catch (System.Exception e)s
{
Console.WriteLine("线程{0}创建失败,已经到达线程的最大数目{1}.", i, i - 1);
break;
}
} Console.ReadLine();
}
}
}
可排队到线程池的操作数仅受可用内存的限制;但是,线程池限制进程中可以同时处于活动状态的线程数。默认情况下,限制每个 CPU 可以使用 25 个辅助线程和 1,000 个 I/O 完成线程。
通过使用 GetMaxThreads 和 SetMaxThreads 方法可以控制最大线程数。 注意
在 .NET Framework 1.0 和 1.1 版中,不能从托管代码中设置线程池大小。承载公共语言运行库的代码可以使用 mscoree.h 中定义的 CorSetMaxThreads 设置该大小。
因为旧线程很快就结束了,因此你可以不断地创建新的线程,看起来就像是个死循环。