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(
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);
}
}
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);
}
}
PersonalizeData,
TimeOut,
false
);
- C# 中的 ThreadPool
- C# ThreadPool
- C# ThreadPool
- C#中的thread和task之 Thread & ThreadPool
- C# ThreadPool类简介
- C# ThreadPool学习笔记
- C# ThreadPool 的改进
- c# ThreadPool 应用实例
- C#线程池ThreadPool
- C# ThreadPool 线程同步
- C# ThreadPool理解
- C# Tutorial - Using The ThreadPool
- C# ThreadPool and WaitHandle Sample
- c#的ThreadPool使用笔记
- C# ThreadPool的简单用法
- C# 浅谈ThreadPool -- 上篇(Enqueue)
- C# 浅谈ThreadPool -- 中篇(ThreadPoolMrg)
- Visual C#中的多线程编程---THREAD类,THREADPOOL类,TIMER类
- oracle服务器是9i,尝试使用10g的客户端进行导出出现错误
- 科普知识------世界洋流[地球上有哪些洋流]
- 关于windows installer出错的解决方案
- ajax访问Web服务(Yahoo搜索的例子)[转]
- oracle安装错误集锦
- C# 中的 ThreadPool
- 联属网络营销
- 如何检测电脑是否安装了.net framework
- 2007-2008中国商业智能市场发展报告
- 关于在winform下DataGrid分页代码
- 关于weblogic pool 一错误调试
- 2007-2008中国商业智能热点新闻
- 迪士尼动画经典大片《海底总动员》两个收获
- 英国小企业家网上促销年赚百万(图)