每次创建一个线程,都会花费几百微秒级别的时间来创建一个私有的局部栈,每个线程默认使用1M的内存。这个可以在使用Thread类的构造函数时设置:
new Thread(new ThreadStart(Go), 2);
new Thread(new ParameterizedThreadStart(Go("hello")), 3);提供的两种构造函数方式都提供了对应的设置线程局部栈的大小。线程池通过共享和回收线程的方式来分配这些内存,这样可以使多线程运行在一个非常细粒度级别上而不影响性能。这对于充分利用多核处理器,使用分而治之的方式进行密集型计算的程序中很有用。同时线程池维护一个所有同时运行的工作线程总数的上限,如果有过多的活动线程就会加重操作系统的负担,使诸如CPU缓存失效等问题,当达到这个上限后,就要进行排队。这个线程队列使得任意并发的应用成为可能,如Web服务器就是这种原理。
有多种方式进入线程池:
CurrentTread.IsThreadPoolThread
static void Main(string[] args)
{
Task.Factory.StartNew(Go);
Console.WriteLine("Is Thread Pool: " + Thread.CurrentThread.IsThreadPoolThread.ToString());
Console.ReadKey();
}
static void Go()
{
Console.Write("Is Thread Pool: " + Thread.CurrentThread.IsThreadPoolThread.ToString());
} static void Main(string[] args)
{
Task<string> task = Task.Factory.StartNew<string>(Go);
Console.WriteLine("Is Thread Pool: " + Thread.CurrentThread.IsThreadPoolThread.ToString());
if (task.IsCompleted)
{
string result = task.Result;
Console.WriteLine(task.IsCompleted.ToString() + result);
}
Console.ReadKey();
}
static string Go()
{
return Thread.CurrentThread.IsThreadPoolThread.ToString();
}static void Main()
{
ThreadPool.QueueUserWorkItem (Go);
ThreadPool.QueueUserWorkItem (Go, 123);
Console.ReadLine();
}
static void Go (object data) // data will be null with the first call.
{
Console.WriteLine ("Hello from the thread pool! " + data);
}static void Main()
{
Func<string, int> method = Work;
method.BeginInvoke ("test", Done, method);
// ...
//
}
static int Work (string s) { return s.Length; }
static void Done (IAsyncResult cookie)
{
var target = (Func<string, int>) cookie.AsyncState;
int result = target.EndInvoke (cookie);
Console.WriteLine ("String length is: " + result);
}ThreadPool.SetMinThreads(50,50);
原文:http://blog.csdn.net/u010487568/article/details/22293087