ThreadPool的例子:using System; using System.Threading; public class Example { public static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps."); // If you comment out the Sleep, the main thread exits before // the thread pool task runs. The thread pool uses background // threads, which do not keep the application running. (This // is a simple example of a race condition.) Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } // This thread procedure performs the task. static void ThreadProc(Object stateInfo) { // No state object was passed to QueueUserWorkItem, so // stateInfo is null. Console.WriteLine("Hello from the thread pool."); } }
//我们的程序中使用ThreadPool来进行一些比较耗时或者需要阻塞的操作。当学要复杂的同步技术,例如事件,或需要对一个现场表调用Join方法时线程池就不能满足需求了.在以下情况中不宜使用ThreadPool而应该使用单独的Thread:
//1,需要为线程指定详细的优先级
//2,线程执行需要很长时间
//3,需要把线程放在单独的线程apartment中
//4,在线程执行中需要对线程操作,如打断,挂起等。搜来的,呵呵~
也可以将与等待操作不相关的工作项排列到线程池。若要请求由线程池中的一个线程来处理工作项,请调用 QueueUserWorkItem 方法。此方法将对将被从线程池中选定的线程调用的方法或委托的引用用作参数。一个工作项排入队列后就无法再取消它。计时器队列中的计时器以及已注册的等待操作也使用线程池。它们的回调函数也会排列到线程池。每个进程都有一个线程池。线程池的默认大小为每个可用处理器有 25 个线程。使用 SetMaxThreads 方法可以更改线程池中的线程数。每个线程使用默认的堆栈大小并按照默认的优先级运行。
using System.Threading;
public class Example {
public static void Main() {
// Queue the task.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread.Sleep(1000); Console.WriteLine("Main thread exits.");
} // This thread procedure performs the task.
static void ThreadProc(Object stateInfo) {
// No state object was passed to QueueUserWorkItem, so
// stateInfo is null.
Console.WriteLine("Hello from the thread pool.");
}
}
2、执行时间较长而又不经常出现的任务,可以单独开辟线程处理,这类任务使用线程池并不会带来明显的性能提升,甚至有可能造成资源浪费。
3、执行时间较长,但经常出现的任务,需要综合考虑具体执行的时间和出现频度,以及自己编写线程管理的复杂度来衡量;一般情况下,我认为单独开辟线
就好。
4、实际作项目时,别忘了不同的机器,性能不一样,多线程处理能力也是不一样的。