相关概念:
线程池可以看做容纳线程的容器;
一个应用程序最多只能有一个线程池;
ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池;
每排入一个工作函数,就相当于请求创建一个线程;
线程池的作用:
线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。
如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止。
什么时候使用ThreadPool?
ThreadPool 示例一 :
using System;
using System.Text;
using System.Threading;
namespace 多线程
{
public class Example
{
public static void Main()
{
// Queue the task.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
static void ThreadProc(Object stateInfo)
{
// No state object was passed to QueueUserWorkItem,
// so stateInfo is null.
Console.WriteLine("Hello from the thread pool.");
}
}
}
using System.Text;
using System.Threading;
namespace 多线程
{
public class Example
{
public static void Main()
{
// Queue the task.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
static void ThreadProc(Object stateInfo)
{
// No state object was passed to QueueUserWorkItem,
// so stateInfo is null.
Console.WriteLine("Hello from the thread pool.");
}
}
}