多线程学习(二)-线程池和定时器——多线程的自动管理

在多线程的程序中,经常会出现两种情况。一种情况下,应用程序中的线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应;而另外一种情况则是线程平常都处于休眠状态,只是周期性地被唤醒。在 .net framework 里边,我们使用 ThreadPool 来对付第一种情况,使用 Timer 来对付第二种情况。

  ThreadPool 类提供一个由系统维护的线程池 —— 可以看作一个线程的容器,该容器需要 Windows 2000 以上版本的系统支持,因为其中某些方法调用了只有高版本的 Windows 才有的 API 函数。你可以使用 ThreadPool.QueueUserWorkItem() 方法将线程安放在线程池里,该方法的原型如下:

  // 将一个线程放进线程池,该线程的 Start() 方法将调用 WaitCallback 代理对象代表的函数
  public static bool QueueUserWorkItem(WaitCallback);
  // 重载的方法如下,参数 object 将传递给 WaitCallback 所代表的方法
  public static bool QueueUserWorkItem(WaitCallback, object);


   要注意的是, ThreadPool 类也是一个静态类,你不能也不必要生成它的对象,而且一旦使用该方法在线程池中添加了一个项目,那么该项目将是没有办法取消的。在这里你无需自己建立线程,只需把你要做的工作写成函数,然后作为参数传递给 ThreadPool.QueueUserWorkItem() 方法就行了,传递的方法就是依靠 WaitCallback 代理对象,而线程的建立、管理、运行等等工作都是由系统自动完成的,你无须考虑那些复杂的细节问题,线程池的优点也就在这里体现出来了,就好像你是公司老板 —— 只需要安排工作,而不必亲自动手。
下面的例程演示了 ThreadPool 的用法。首先程序创建了一个 ManualResetEvent 对象,该对象就像一个信号灯,可以利用它的信号来通知其它线程,本例中当线程池中所有线程工作都完成以后, ManualResetEvent 的对象将被设置为有信号,从而通知主线程继续运行。它有几个重要的方法: Reset() Set() WaitOne() 。初始化该对象时,用户可以指定其默认的状态(有信号 / 无信号),在初始化以后,该对象将保持原来的状态不变直到它的 Reset() 或者 Set() 方法被调用, Reset() 方法将其设置为无信号状态, Set() 方法将其设置为有信号状态。 WaitOne() 方法使当前线程挂起直到 ManualResetEvent 对象处于有信号状态,此时该线程将被激活。然后,程序将向线程池中添加工作项,这些以函数形式提供的工作项被系统用来初始化自动建立的线程。当所有的线程都运行完了以后, ManualResetEvent.Set() 方法被调用,因为调用了 ManualResetEvent.WaitOne() 方法而处在等待状态的主线程将接收到这个信号,于是它接着往下执行,完成后边的工作。

  using System;
  using System.Collections;

  using System.Threading;

  // 这是用来保存信息的数据结构,将作为参数被传递
  public class SomeState

  {
   public int Cookie;
   public SomeState(int iCookie)
   {
     Cookie = iCookie;
   }
  }


  public class Alpha
  {
   public Hashtable HashCount;
   public ManualResetEvent eventX;
   public static int iCount = 0;
   public static int iMaxCount = 0;
   public Alpha(int MaxCount)
   {
     HashCount = new Hashtable(MaxCount);
     iMaxCount = MaxCount;
   }

   file:// 线程池里的线程将调用 Beta() 方法
   public void Beta(Object state)
   {
     // 输出当前线程的 hash 编码值和 Cookie 的值
     Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(),
     ((SomeState)state).Cookie);
     Console.WriteLine("HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}", HashCount.Count, Thread.CurrentThread.GetHashCode());
     lock (HashCount)
     {
     file:// 如果当前的 Hash 表中没有当前线程的 Hash 值,则添加之
     if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
       HashCount.Add (Thread.CurrentThread.GetHashCode(), 0);
     HashCount[Thread.CurrentThread.GetHashCode()] =
((int)HashCount[Thread.CurrentThread.GetHashCode()])+1;
     }

     int iX = 2000;
     Thread.Sleep(iX);
     //Interlocked.Increment() 操作是一个原子操作,具体请看下面说明
     Interlocked.Increment(ref iCount);
     if (iCount == iMaxCount)
     {
     Console.WriteLine();
     Console.WriteLine("Setting eventX ");
     eventX.Set();
     }
   }
  }


  public class SimplePool
  {
   public static int Main(string[] args)
   {
     Console.WriteLine("Thread Pool Sample:");
     bool W2K = false;
     int MaxCount = 10;// 允许线程池中运行最多 10 个线程
     // 新建 ManualResetEvent 对象并且初始化为无信号状态
     ManualResetEvent eventX = new ManualResetEvent(false);
     Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount);
     Alpha oAlpha = new Alpha(MaxCount); file:// 创建工作项
     // 注意初始化 oAlpha 对象的 eventX 属性
     oAlpha.eventX = eventX;
     Console.WriteLine("Queue to Thread Pool 0");
     try
     {
     file:// 将工作项装入线程池
     file:// 这里要用到 Windows 2000 以上版本才有的 API ,所以可能出现 NotSupportException 异常
     ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),
     new SomeState(0));
     W2K = true;
     }
     catch (NotSupportedException)
     {
     Console.WriteLine("These API's may fail when called on a non-Windows 2000 system.");
     W2K = false;
     }
     if (W2K)// 如果当前系统支持 ThreadPool 的方法 .
     {
     for (int iItem=1;iItem < MaxCount;iItem++)
     {
       // 插入队列元素
       Console.WriteLine("Queue to Thread Pool {0}", iItem);
       ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem));
     }
     Console.WriteLine("Waiting for Thread Pool to drain");
     file:// 等待事件的完成,即线程调用 ManualResetEvent.Set() 方法
     eventX.WaitOne(Timeout.Infinite,true);
     file://WaitOne() 方法使调用它的线程等待直到 eventX.Set() 方法被调用
     Console.WriteLine("Thread Pool has been drained (Event fired)");
     Console.WriteLine();
     Console.WriteLine("Load across threads");
     foreach(object o in oAlpha.HashCount.Keys)
     Console.WriteLine("{0} {1}", o, oAlpha.HashCount[o]);
     }
     Console.ReadLine();
     return 0;

   }
  }

   程序中有些小地方应该引起我们的注意。 SomeState 类是一个保存信息的数据结构,在上面的程序中,它作为参数被传递给每一个线程,你很容易就能理解这个,因为你需要把一些有用的信息封装起来提供给线程,而这种方式是非常有效的。程序出现的 InterLocked 类也是专为多线程程序而存在的,它提供了一些有用的原子操作,所谓原子操作就是在多线程程序中,如果这个线程调用这个操作修改一个变量,那么其他线程就不能修改这个变量了,这跟 lock 关键字在本质上是一样的。

   我们应该彻底地分析上面的程序,把握住线程池的本质,理解它存在的意义是什么,这样我们才能得心应手地使用它。下面是该程序的输出结果:
  Thread Pool Sample:
  Queuing 10 items to Thread Pool
  Queue to Thread Pool 0
  Queue to Thread Pool 1
  ...
  ...
  Queue to Thread Pool 9
  Waiting for Thread Pool to drain
  98 0 :
  HashCount.Count==0, Thread.CurrentThread.GetHashCode()==98
  100 1 :

  HashCount.Count==1, Thread.CurrentThread.GetHashCode()==100
  98 2 :
  ...
  ...
  Setting eventX
  Thread Pool has been drained (Event fired)
  Load across threads
  101 2
  100 3
  98 4
  102 1

   ThreadPool 类不同, Timer 类的作用是设置一个定时器,定时执行用户指定的函数,而这个函数的传递是靠另外一个代理对象 TimerCallback ,它必须在创建 Timer 对象时就指定,并且不能更改。定时器启动后,系统将自动建立一个新的线程,并且在这个线程里执行用户指定的函数。下面的语句初始化了一个 Timer 对象:
  Timer timer = new Timer(timerDelegate, s,1000, 1000);

    第一个参数指定了 TimerCallback 代理对象;第二个参数的意义跟上面提到的 WaitCallback 代理对象的一样,作为一个传递数据的对象传递给要调用的方法;第三个参数是延迟时间 —— 计时开始的时刻距现在的时间,单位是毫秒;第四个参数是定时器的时间间隔 —— 计时开始以后,每隔这么长的一段时间, TimerCallback 所代表的方法将被调用一次,单位也是毫秒。这句话的意思就是将定时器的延迟时间和时间间隔都设为 1 秒钟。

   定时器的设置是可以改变的,只要调用 Timer.Change() 方法,这是一个参数类型重载的方法,一般使用的原型如下:
   public bool Change(long, long);

  下面这段代码将前边设置的定时器修改了一下:
   timer.Change(10000,2000);

   很显然,定时器 timer 的时间间隔被重新设置为 2 秒,停止计时 10 秒后生效。

   下面这段程序演示了 Timer 类的用法。

  using System;

  using System.Threading;
  class TimerExampleState
  {
   public int counter = 0;
   public Timer tmr;
  }


  class App
  {
   public static void Main()
   {
     TimerExampleState s = new TimerExampleState();

     // 创建代理对象 TimerCallback ,该代理将被定时调用
     TimerCallback timerDelegate = new TimerCallback(CheckStatus);

     // 创建一个时间间隔为 1s 的定时器
     Timer timer = new Timer(timerDelegate, s,1000, 1000);
     s.tmr = timer;

     // 主线程停下来等待 Timer 对象的终止
     while(s.tmr != null)
     Thread.Sleep(0);
     Console.WriteLine("Timer example done.");
     Console.ReadLine();
   }
   file:// 下面是被定时调用的方法

   static void CheckStatus(Object state)
   {
     TimerExampleState s =(TimerExampleState)state;
     s.counter++;
     Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
     if(s.counter == 5)
     {
     file:// 使用 Change 方法改变了时间间隔
     (s.tmr).Change(10000,2000);
     Console.WriteLine("changed...");
     }
     if(s.counter == 10)
     {
     Console.WriteLine("disposing of timer...");
     s.tmr.Dispose();
     s.tmr = null;
     }
   }
  }

   程序首先创建了一个定时器,它将在创建 1 秒之后开始每隔 1 秒调用一次 CheckStatus() 方法,当调用 5 次以后,在 CheckStatus() 方法中修改了时间间隔为 2 秒,并且指定在 10 秒后重新开始。当计数达到 10 次,调用 Timer.Dispose() 方法删除了 timer 对象,主线程于是跳出循环,终止程序。程序执行的结果如下:


   上面就是对 ThreadPool Timer 两个类的简单介绍,充分利用系统提供的功能,可以为我们省去很多时间和精力 —— 特别是对很容易出错的多线程程序。同时我们也可以看到 .net Framework 强大的内置对象,这些将对我们的编程带来莫大的方便。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值