C# 中的 ThreadPool

来源:互联网 发布:网络卫星电视直播软件 编辑:程序博客网 时间:2024/06/01 08:47

System.Threading.TheadPool 可以看做是若干个Thread组成的队列。

一个进程仅有一个ThreadPool,所以ThreadPool类中都是静态方法。ThreadPool会在首次调用注册线程方法时被创建。(ThreadPool.QueueUserWorkItem、ThreadPool.RegisterWaitForSingleObject等)。

一个ThreadPool里面注册的线程拥有默认的堆栈大小,默认的优先级。并且,他们都存在于多线程空间(Multithreaded apartment)中。

ThreadPool中的Thread不能手动取消,也不用手动开始。所以ThreadPool并不适用比较长的线程。你要做的只是把一个WaitCallback委托塞给ThreadPool,然后剩下的工作将由系统自动完成。系统会在ThreadPool的线程队列中一一启动线程。

当线程池满时,多余的线程会在队列里排队,当线程池空闲时,系统自动掉入排队的线程,以保持系统利用率。

在以下情况中不宜使用ThreadPool而应该使用单独的Thread:
1,需要为线程指定详细的优先级
2,线程执行需要很长时间
3,需要把线程放在单独的线程apartment中
4,在线程执行中需要对线程操作,如打断,挂起等。

Threadpool中线程的注册:

委托:
ThreadPool.QueueUserWorkItem(

new WaitCallback(FunctionCall), PersonalizeDataForTherad);

Timer:
ThreadPool.RegisterWaitForSingleObject(
AutoResetEventObject,

代码示例:

//Coding by zhl
using System;
using System.Threading;

public class TestThreadPool {
    
//Entry of Application
    public static void Main() {
        
//Declare delegate WaitCallback
        WaitCallback wc = new WaitCallback(run);
        
for(int i = 0; i < 10; i++)
            
//Assign thread in the thread pool
            ThreadPool.QueueUserWorkItem(wc,i);
        
        
while (true)
            
if(Console.ReadLine().ToLower()=="exit"break;
    }

    
//Function which is pointed by delegate WaitCallback
    public static void run(object state) {
        Console.WriteLine(
"Starting...");
        Console.WriteLine(
"Thread {0} is started.",state);
        Thread.Sleep(
10000);
        Console.WriteLine(
"Thread {0} is shutted down.",state);
    }

    
}
new WaitOrTimerCallback(FunctionCall),
PersonalizeData,
TimeOut,
false
);
原创粉丝点击