线程池之定时器

如果你开发过Win32应用程序,你应该知道设置定时器是它API中的一部分。在这种情况下,你必须创建一个window来接收WM_TIMER的消息。我们所面临的第一个问题是,创建一个window来接收消息,但你却无法控制台应用程序中应用。其二,基于消息的执行有时不是很精确,并且如果你的应用程序要处理很多消息时,那情况将是很糟糕的。
一种改进方法是在WIn32定时器的基础上,为每一个定时器创建一个线程,并让它sleep一段时间,当到达定时时,就调用相应的方法。这种方式,使我们摆脱了windows的消息机制。能够更精确并能用于控制台程序。通用代码如下:
class MainApp
{
   static void Main()
   {
      MyTimer myTimer = new MyTimer(2000);  //自定义定时器
      Console.ReadLine();
   }
}
class MyTimer
{
   int m_period;

   public MyTimer(int period)
   {
      Thread thread;

      m_period = period;
      thread = new Thread(new ThreadStart(TimerThread)); //在定时器生成线程
      thread.Start();
   }
   void TimerThread()
   {
      Thread.Sleep(m_period);
      OnTimer();
   }
   void OnTimer()
   {
      Console.WriteLine("OnTimer");
   }
}
 
下面这种方法更好:
class MainApp
{
static void Main()
{
Timer timer1 = new Timer(new TimerCallback(OnTimer), 1, 0, 2000);
Timer timer2 = new Timer(new TimerCallback(OnTimer), 2, 0, 3000);

Console.ReadLine();
}
static void OnTimer(object obj)
{
Console.WriteLine("Timer: {0} Thread: {1} Is pool thread: {2}",
(int)obj,
Thread.CurrentThread.GetHashCode(),
Thread.CurrentThread.IsThreadPoolThread);
}
}

The output will be the following:

Timer: 1 Thread: 2 Is pool thread: True
Timer: 2 Thread: 2 Is pool thread: True
Timer: 1 Thread: 2 Is pool thread: True
Timer: 2 Thread: 2 Is pool thread: True
Timer: 1 Thread: 2 Is pool thread: True
Timer: 1 Thread: 2 Is pool thread: True
Timer: 2 Thread: 2 Is pool thread: True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值