现在的位置: 首页 > 综合 > 正文

.NET 的三种定时器整理

2013年05月16日 ⁄ 综合 ⁄ 共 2013字 ⁄ 字号 评论关闭

 System.Windows.Forms.Timer, Windows 计时器是为单线程环境设计的,其中,UI 线程用于执行处理。Windows 计时器的精度限定为 55 毫秒。这些传统计时器要求用户代码有一个可用的 UI 消息泵,而且总是在同一个线程中操作,或者将调用封送到另一个线程。对于 COM 组件来说,这样会降低性能。

System.Timers.Timer, 基于服务器的计时器是为在多线程环境下与辅助线程一起使用而设计的。由于它们使用不同的体系结构,因此基于服务器的计时器可能比 Windows 计时器精确得多。服务器计时器可以在线程之间移动来处理引发的事件。

System.Threading.Timer, 对消息不在线程上发送的方案中,线程计时器是非常有用的。例如,基于 Windows 的计时器依赖于操作系统计时器的支持,如果不在线程上发送消息,与计时器相关的事件将不会发生。在这种情况下,线程计时器就非常有用。

使用例子:

System.Windows.Forms.Timer{
public static int Main() {
       
/* Adds the event and the event handler for the method that will 
          process the timer event to the timer. 
*/

       myTimer.Tick 
+= new EventHandler(TimerEventProcessor);
 
       
// Sets the timer interval to 5 seconds.
       myTimer.Interval = 5000;
       myTimer.Start();
 
       
// Runs the timer, and raises the event.
       while(exitFlag == false{
          
// Processes all the events in the queue.
          Application.DoEvents();
       }

    
return 0;
    }

}

System.Timers.Timer
{
     
public static void Main()
     
{
       
// Create a new Timer with Interval set to 10 seconds.
       System.Timers.Timer aTimer = new System.Timers.Timer(10000);
       aTimer.Elapsed
+=new ElapsedEventHandler(OnTimedEvent);
       
// Only raise the event the first time Interval elapses.
       aTimer.AutoReset = false;
       aTimer.Enabled 
= true;
 
       Console.WriteLine(
"Press 'q' to quit the sample.");
       
while(Console.Read()!='q');
     }

 
     
// Specify what you want to happen when the event is raised.
     private static void OnTimedEvent(object source, ElapsedEventArgs e) 
     
{
       Console.WriteLine(
"Hello World!");
     }

}
                                                       
System.Threading.Timer  
{                                                          
   TimerCallback timerDelegate 
= new TimerCallback(CheckStatus);
                                                            
   
// Create a timer that waits one second, then invokes every second.
   Timer timer = new Timer(timerDelegate, s,10001000);    
}

抱歉!评论已关闭.