.NET线程池

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Text;   
  4. using System.Collections;   
  5. using System.Threading;   
  6. using System.Net.Sockets;   
  7.   
  8. namespace SpiderClient   
  9. {   
  10.     class ThreadPool   
  11.     {   
  12.   
  13.         //本客户度连接sockt   
  14.   
  15.         private Client c = null;   
  16.   
  17.         //线程池中数量   
  18.         private int threadcount;   
  19.   
  20.         //保存所有线程池对象   
  21.         private ArrayList threads = null;   
  22.   
  23.         //保存所有mywebrequest对象   
  24.         private ArrayList requests = null;   
  25.   
  26.         //线程时候停止 可以外部控制   
  27.         public bool isstopthread = false;   
  28.   
  29.         public ThreadPool(Client _c,int _threadcount)   
  30.         {   
  31.             //   
  32.             c = _c;   
  33.             threadcount = _threadcount;   
  34.             threads = new ArrayList();   
  35.             requests = new ArrayList();   
  36.   
  37.         }   
  38.   
  39.         public static ThreadPool CreateThreadPool(ThreadPool tp, Client _c, int _threadcount)   
  40.         {   
  41.             if (tp == null)   
  42.             {   
  43.                 return new ThreadPool(_c, _threadcount);   
  44.             }   
  45.             else  
  46.             {   
  47.                 tp.threads.Clear();   
  48.                 tp.requests.Clear();   
  49.   
  50.                 return tp;   
  51.             }   
  52.         }   
  53.   
  54.         public void StartPool()   
  55.         {   
  56.             Thread t = null;   
  57.             MyWebRequest mwr = null;   
  58.             for (int i = 0; i < threadcount; i++)   
  59.             {   
  60.                 t = new Thread(new ParameterizedThreadStart(ThreadFunc));   
  61.                 requests.Add(mwr);   
  62.                 threads.Add(t);   
  63.                 t.Start(i);   
  64.             }   
  65.         }   
  66.   
  67.   
  68.         public void StopAllThreads()   
  69.         {   
  70.             isstopthread = true;   
  71.             for (int i = 0; i < threadcount; i++)   
  72.             {   
  73.                 Thread t = (Thread)threads[i];   
  74.                 if (t != null)   
  75.                 {   
  76.                     if (t.ThreadState == ThreadState.Suspended)   
  77.                     {   
  78.                         t.Start();   
  79.                     }   
  80.                     t.Abort();   
  81.                 }   
  82.             }   
  83.         }   
  84.   
  85.         private void ThreadFunc(object o)   
  86.         {   
  87.             int i = (int)o;   
  88.             while (!isstopthread)   
  89.             {   
  90.                 Thread.Sleep(100);   
  91.             }   
  92.         }   
  93.     }   
  94. }   

=========================================================================

简单代码如下:

 
  1. using System;   
  2. using System.Threading;   
  3. public class Example {   
  4.     public static void Main() {   
  5.         // Queue the task.   
  6.         ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));   
  7.            
  8.         Console.WriteLine("Main thread does some work, then sleeps.");   
  9.         // If you comment out the Sleep, the main thread exits before   
  10.         // the thread pool task runs.  The thread pool uses background   
  11.         // threads, which do not keep the application running.  (This   
  12.         // is a simple example of a race condition.)   
  13.         Thread.Sleep(1000);   
  14.   
  15.         Console.WriteLine("Main thread exits.");   
  16.     }   
  17.   
  18.     // This thread procedure performs the task.   
  19.     static void ThreadProc(Object stateInfo) {   
  20.         // No state object was passed to QueueUserWorkItem, so    
  21.         // stateInfo is null.   
  22.         Console.WriteLine("Hello from the thread pool.");   
  23.     }   
  24. }   



另外一个例子是关于自定义数据参与线程池处理的代码:

 
  1. using System;   
  2. using System.Threading;   
  3.   
  4. // TaskInfo holds state information for a task that will be   
  5. // executed by a ThreadPool thread.   
  6. public class TaskInfo {   
  7.     // State information for the task.  These members   
  8.     // can be implemented as read-only properties, read/write   
  9.     // properties with validation, and so on, as required.   
  10.     public string Boilerplate;   
  11.     public int Value;   
  12.   
  13.     // Public constructor provides an easy way to supply all   
  14.     // the information needed for the task.   
  15.     public TaskInfo(string text, int number) {   
  16.         Boilerplate = text;   
  17.         Value = number;   
  18.     }   
  19. }   
  20.   
  21. public class Example {   
  22.     public static void Main() {   
  23.         // Create an object containing the information needed   
  24.         // for the task.   
  25.         TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);   
  26.   
  27.         // Queue the task and data.   
  28.         if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {       
  29.             Console.WriteLine("Main thread does some work, then sleeps.");   
  30.   
  31.             // If you comment out the Sleep, the main thread exits before   
  32.             // the ThreadPool task has a chance to run.  ThreadPool uses    
  33.             // background threads, which do not keep the application    
  34.             // running.  (This is a simple example of a race condition.)   
  35.             Thread.Sleep(1000);   
  36.   
  37.             Console.WriteLine("Main thread exits.");   
  38.         }   
  39.         else {   
  40.             Console.WriteLine("Unable to queue ThreadPool request.");    
  41.         }   
  42.     }   
  43.   
  44.     // The thread procedure performs the independent task, in this case   
  45.     // formatting and printing a very simple report.   
  46.     //   
  47.     static void ThreadProc(Object stateInfo) {   
  48.         TaskInfo ti = (TaskInfo) stateInfo;   
  49.         Console.WriteLine(ti.Boilerplate, ti.Value);    
  50.     }   
  51. }   
SmartThreadPool是大名鼎鼎的.Net线程池项目,基于.Net开发,比.Net内置的线程池更胜一筹。1、为什么需要使用线程池(Thread Pool)减少线程间上下文切换。线程执行一定的时间片后,系统会自动把cpu切换给另一个线程使用,这时还需要保存当 前的线程上下文状态,并加载新线程的上下文状态。当程序中有大量的线程时,每个线程分得的时间片会越来越少,可能会出现线程未处理多少操作,就需要切换到 另一线程,这样频繁的线程间上下文切换会花费大量的cpu时间。减少内存占用。系统每创建一条物理线程,需要大概花费1MB的内存空间,许多程序喜欢先创建多条物理线程,并 周期轮询来处理各自的任务,这样既消耗了线程上下文切换的时间,还浪费了内存。这些任务可能只需要一条线程就能满足要求。假如某一任务需要执行较长的周 期,线程池还可以自动增加线程,并在空闲时,销毁线程,释放占用的内存。2、为什么不使用.Net默认的线程池.Net默认的线程池(ThreadPool)是一个静态类,所以是没办法自己创建一个新的程序池的。默认的线程池与应用程序域 (AppDomain)挂钩,一个AppDomain只有一个线程池。假如在线程池中执行了一个周期较长的任务,一直占用着其中一个线程,可能就会影响到 应用程序域中的其他程序的性能。例如,假如在Asp.Net线程池中执行一个周期较长的任务,就会影响请求的并发处理能力(线程池默认有个最大线程 数)。 3、SmartThreadPool特性和优点    SmartThreadPool特性如下:可创建线程池实例。可动态调整线程池工作线程数量。WorkItem 可以返回信息。未执行 WorkItem 可被取消。WorkItem 执行时可使用调用者上下文。调用者可等待多个或全部 WorkItem 执行结束。WorkItem 允许拥有一个执行结束时被执行的 PostExecute 回调委托。可以向 WorkItem 传递一个状态对象,并且会在执行结束时自动调用 IDisposable.Dispose()。WorkItem 异常会传递给调用者。支持 WorkItem 分组。可挂起线程池或分组。可以设置 WorkItem 优先级。可以设置线程优先级。4、使用示例 最简单的使用方法:// 创建一个线程池 SmartThreadPool smartThreadPool = new SmartThreadPool();    // 执行任务 smartThreadPool.QueueWorkItem(() => {      Console.WriteLine("Hello World!"); });带返回值的任务:// 创建一个线程池 SmartThreadPool smartThreadPool = new SmartThreadPool();   // 执行任务 var result = smartThreadPool.QueueWorkItem(() => {     var sum = 0;     for (var i = 0; i  {     //模拟计算较长时间     Thread.Sleep(5000);       return 3; });   var result2 = smartThreadPool.QueueWorkItem(() => {     //模拟计算较长时间     Thread.Sleep(3000);       return 5; });   bool success = SmartThreadPool.WaitAll(     new IWorkItemResult[] { result1, result2 });   if (success) {     // 输出结果     Console.WriteLine(result1.Result);     Console.WriteLine(result2.Result); }5、结论 使用SmartThreadPool可以简单就实现支持多线程的程序,由线程池来管理线程,可以减少死锁的出现。SmartThreadPool还支持简单的生产者-消费者模式,当不需要对任务进行持久化时,还是很好用的。 6、扩展阅读 http://www.codeproject.com/KB/threads/smartthreadpool.aspx http://smartthreadpool.codeplex.com/http://www.albahari.com/threading/ 标签:线程池
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值