C#中的Timer和DispatcherTimer使用實(shí)例
Timer組件是基于服務(wù)器的計時器,通過設(shè)置時間間隔Interval,周期性的觸發(fā)Elapsed事件。
用法如下:
class Program {
static System.Timers.Timer Timer1 = new System.Timers.Timer();
static void Main() {
Timer1.Interval = 1000;
Timer1.Elapsed += new ElapsedEventHandler(PeriodicTaskHandler);
Timer1.Start();
Console.ReadLine();
}
static void PeriodicTaskHandler(object sender, ElapsedEventArgs e) {
string str =Thread.CurrentThread.ManagedThreadId.ToString()+"##" +"Timer1" +"##" + e.SignalTime.ToLongTimeString();
Console.WriteLine(str);
}
}
DispatcherTimer:Dispatcher隊(duì)列中的計時器,不能保證正好在設(shè)置的時間間隔發(fā)生時執(zhí)行計時器,但能保證不會在時間間隔發(fā)生之前執(zhí)行計時器。這是因?yàn)?nbsp; DispatcherTimer的操作也是放置在Dispatcher隊(duì)列中的,何時執(zhí)行DispatcherTimer操作取決于隊(duì)列中其他作業(yè)及其優(yōu)先級。
在WPF應(yīng)用程序中
Timer的Elapsed事件綁定的方法沒有運(yùn)行在UI線程上,如果要訪問UI線程上的對象,需要利用Invoke或BeginInvoke 將操作發(fā)布到UI線程的Dispatcher上。
用法如下:
private void Button_Click(object sender, RoutedEventArgs e) {
Timer timer = new Timer();
timer.Interval = 1000;
timer.Start();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
void timer_Elapsed(object sender, ElapsedEventArgs e) {
i++;
this.Dispatcher.Invoke(new Action(() => {
test.Content = i.ToString();
}));
}
private int i = 0;
DispatcherTimer與Dispatcher都運(yùn)行于相同的線程,并且可以在DispatcherTimer上設(shè)置DispatcherPriority。
用法
private void Button_Click(object sender, RoutedEventArgs e) {
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e) {
i++;
Test.Content = i.ToString();
}
private int i = 0;
private DispatcherTimer timer = new DispatcherTimer();
- C#中高精度計時器Stopwatch的用法詳解
- C#使用Stopwatch實(shí)現(xiàn)計時功能
- C#?Stopwatch實(shí)現(xiàn)計算代碼運(yùn)行時間
- C#中Stopwatch的使用及說明
- C# 中使用Stopwatch計時器實(shí)現(xiàn)暫停計時繼續(xù)計時功能
- 如何使用C# Stopwatch 測量微秒級精確度
- .NET/C# 使用Stopwatch測量運(yùn)行時間
- C#使用StopWatch獲取程序毫秒級執(zhí)行時間的方法
- C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
- C#中的三種定時計時器Timer用法介紹
- C#中三種Timer計時器的詳細(xì)用法
- 詳解C#中的定時器Timer類及其垃圾回收機(jī)制
- C#使用timer實(shí)現(xiàn)的簡單鬧鐘程序
- [C#].NET中幾種Timer的使用實(shí)例
- C# 中Stopwatch和timer的實(shí)現(xiàn)示例
相關(guān)文章
C#實(shí)現(xiàn)文件讀寫到SQLite數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了使用?C#?將文件讀寫到?SQLite?數(shù)據(jù)庫的幾種方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2025-01-01
WPF PasswordBox進(jìn)行數(shù)據(jù)綁定方法
有的時候會遇見PasswordBox的Password屬性不是依賴屬性,因此無法進(jìn)行數(shù)據(jù)綁定。本文介紹如何通過添加附加屬性解決該問題,有此問題的同學(xué)可以參考下本文2021-06-06
C# winform實(shí)現(xiàn)登陸次數(shù)限制
這篇文章主要介紹了C# winform實(shí)現(xiàn)登陸次數(shù)限制,相信大家都遇到過網(wǎng)站在用戶多次輸錯密碼之后會自動把賬戶凍結(jié)的情況,這種功能如何實(shí)現(xiàn),下面小編為大家分享實(shí)現(xiàn)方法2016-05-05
C#使用Spire.Doc實(shí)現(xiàn)Word轉(zhuǎn)換為TIFF的代碼示例
在需要將Word文檔高質(zhì)量轉(zhuǎn)換為圖像格式的場景中(如生成文檔預(yù)覽或歸檔),TIFF是理想選擇,使用Spire.Doc for .NET,開發(fā)者只需幾行C#代碼即可實(shí)現(xiàn)批量轉(zhuǎn)換,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2025-08-08
C#實(shí)現(xiàn)將TextBox綁定為KindEditor富文本
KindEditor?依靠出色的用戶體驗(yàn)和領(lǐng)先的技術(shù)提供富文本編輯功能,是一款非常受歡迎的HTML在線編輯器,下面我們就來看看C#如何將TextBox綁定為KindEditor富文本吧2024-04-04

