1.定义在System.Windows.Forms里
2.定义在System.Threading.Timer类里
3.定义在System.Timers.Timer类里
System.Windows.Forms.Timer是运用于WinForm中的,它是经由过程Windows音讯机制完成的,相似于VB或Delphi中的Timer控件,内部运用API SetTimer完成的。它的重要瑕玷是计时不准确,而且必须有音讯轮回,Console Application(控制台运用程序)没法运用。
System.Timers.Timer和System.Threading.Timer异常相似,它们是经由过程.NET Thread Pool完成的,轻量,计时准确,对运用程序、音讯没有迥殊的请求。 System.Timers.Timer还能够运用于WinForm,完整庖代上面的Timer控件。它们的瑕玷是不支持直接的拖放,须要手工编码。
下面举例说明,System.Timers.Timer定时器的用法。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Timers; using System.Runtime.InteropServices; using System.Threading; namespace Timer001 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //实例化Timer类 System.Timers.Timer aTimer = new System.Timers.Timer(); private void button1_Click(object sender, EventArgs e) { this.SetTimerParam(); } private void test(object source, System.Timers.ElapsedEventArgs e) { MessageBox.Show(DateTime.Now.ToString()); } public void SetTimerParam() { //到时刻的时刻实行事宜 aTimer.Elapsed += new ElapsedEventHandler(test); aTimer.Interval = 1000; aTimer.AutoReset = true;//实行一次 false,一向实行true //是不是实行System.Timers.Timer.Elapsed事宜 aTimer.Enabled = true; } } }
完成的结果是:每秒弹出体系当前时刻,如下图:
以上就是C# Timer 定时器运用的内容,更多相关内容请关注ki4网(www.ki4.cn)!