浅谈.NET中可用的定时器和计时器【上篇】
<div id="cnblogs_post_body">.net中的计时问题可能每个人都会遇到,但是很少有人系统的总结,Baidu了下,无果,故写作本文。本文旨在总结.net中可用的各种计时方法,介绍的是DebugLZQ知道的几种.net中的定时、计时方法。并进行了我所知道的分析(重点)和简单使用,并不涉及更深层次的讨论。
进入正题:
定时器是系统常用的组件之一,程序员可以根据自己的需求定制一个定时器类型,也可以使用.net内建的定时器类型。在.net中一共为程序员提供了3种定时器:
[*]System.Windows.Forms.Timer类型
[*]System.Threading.Timer类型
[*]System.Timers.Timer类型
概括来说,这3种类型都实现了定时的功能。程序员通常需要做的是为定时器设置一个间断时间,设置定时器到时的处理方法,然后可以等待定时器不断地计时和出发时间处理,下面详细介绍下这三种类型的特点。
[*]System.Windows.Forms.Timer类型
从这个定时器的命名空间可以看出,.net设计这个定时器的目的是为了方便程序员在Window Form中使用定时器。当一个System.Windows.Forms.Timer类被构造时,当前定时器会和当前线程进行关联。而当计时器的计时达到后,一个定时器消息将被插入到当前线程的消息队列中。当前线程逐一处理消息中的所有消息,并一一派发给各自的处理方法。这样的机制和利用工作者进程定时有很大的区别,事实上,System.Windows.Forms.Timer类型并没有涉及多线程的操作,定时器的设置、定时方法的执行都在同一个线程之上。
这就意味着System.Windows.Forms.Timer并不能准确计时,事实上,当消息阻塞时,定时器的误差将非常大,因为定时器消息只能等待在前面的所有消息处理完后才能得到处理。但是因为System.Windows.Forms.Timer类型的定时器并不涉及多线程的操作,因此是线程安全的,不会发生回调方法重入的问题。
简单的使用如下:
<div class="cnblogs_code">public class Class1 { static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer(); static int alarmCounter = 1; static bool exitFlag = false; // This is the method to run when the timer is raised. private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { myTimer.Stop(); // Displays a message box asking whether to continue running the timer. if(MessageBox.Show("Continue running?", "Count is: " + alarmCounter, MessageBoxButtons.YesNo) == DialogResult.Yes) { // Restarts the timer and increments the counter. alarmCounter +=1; myTimer.Enabled = true; } else { // Stops the timer. exitFlag = true; } } 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; } }
页:
[1]