C#中timer類的用法
關於C#中timer類 在C#里關於定時器類就有3個
1.定義在System.Windows.Forms里
2.定義在System.Threading.Timer類里
3.定義在System.Timers.Timer類里
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類
//實例化Timer類,設置間隔時間為10000毫秒;
System.Timers.Timer t = new System.Timers.Timer(10000);
//到達時間的時候執行事件;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
t.AutoReset = true;//設置是執行一次(false)還是一直執行(true);
t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件;
====================================
自己寫的一個用System.Timer類的方法
1 public class BF_CheckUpdate
2 {
3 private static object LockObject = new Object();
4
5 // 定義數據檢查Timer
6 private static Timer CheckUpdatetimer = new Timer();
7
8 // 檢查更新鎖
9 private static int CheckUpDateLock = 0;
10
11 ///
12 /// 設定數據檢查Timer參數
13 ///
14 internal static void GetTimerStart()
15 {
16 // 循環間隔時間(10分鍾)
17 CheckUpdatetimer.Interval = 600000;
18 // 允許Timer執行
19 CheckUpdatetimer.Enabled = true;
20 // 定義回調
21 CheckUpdatetimer.Elapsed += new ElapsedEventHandler(CheckUpdatetimer_Elapsed);
22 // 定義多次循環
23 CheckUpdatetimer.AutoReset = true;
24 }
25
26 ///
27 /// timer事件
28 ///
29 ///
30 ///
31 private static void CheckUpdatetimer_Elapsed(object sender, ElapsedEventArgs e)
32 {
33 // 加鎖檢查更新鎖
34 lock (LockObject)
35 {
36 if (CheckUpDateLock == 0) CheckUpDateLock = 1;
37 else return;
38 }
39
40 //More code goes here
.
41 //具體實現功能的方法
42 Check();
43 // 解鎖更新檢查鎖
44 lock (LockObject)
45 {
46 CheckUpDateLock = 0;
47 }
48 }
49 }
2 {
3 private static object LockObject = new Object();
4
5 // 定義數據檢查Timer
6 private static Timer CheckUpdatetimer = new Timer();
7
8 // 檢查更新鎖
9 private static int CheckUpDateLock = 0;
10
11 ///
12 /// 設定數據檢查Timer參數
13 ///
14 internal static void GetTimerStart()
15 {
16 // 循環間隔時間(10分鍾)
17 CheckUpdatetimer.Interval = 600000;
18 // 允許Timer執行
19 CheckUpdatetimer.Enabled = true;
20 // 定義回調
21 CheckUpdatetimer.Elapsed += new ElapsedEventHandler(CheckUpdatetimer_Elapsed);
22 // 定義多次循環
23 CheckUpdatetimer.AutoReset = true;
24 }
25
26 ///
27 /// timer事件
28 ///
29 ///
30 ///
31 private static void CheckUpdatetimer_Elapsed(object sender, ElapsedEventArgs e)
32 {
33 // 加鎖檢查更新鎖
34 lock (LockObject)
35 {
36 if (CheckUpDateLock == 0) CheckUpDateLock = 1;
37 else return;
38 }
39
40 //More code goes here


41 //具體實現功能的方法
42 Check();
43 // 解鎖更新檢查鎖
44 lock (LockObject)
45 {
46 CheckUpDateLock = 0;
47 }
48 }
49 }