C# 计时器用法(DispatcherTimer、System.Timers.Timer、System.Threading.Timer)
首先,我觉得三种计时器最大的区别是:DispatcherTimer触发的内容会直接转到主线程去执行(耗时操作会卡住主线程),另外两个则是在副线程执行,如果需要修改界面,则需要手动转到主线程。
DispatcherTimer:
DispatcherTimer _timer; public void TestDispatcherTimer() { _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += _timer_Tick; _timer.Start(); } private void _timer_Tick(object sender, EventArgs e) { try { Trace.WriteLine("Test DispatcherTimer"); _timer.Stop(); } catch (Exception ex) { Trace.WriteLine("Error"); _timer.Stop(); _timer.Start(); } }
System.Timers.Timer:
System.Timers.Timer _timer; public void TestTimersTimer() { _timer = new System.Timers.Timer(); _timer.Interval = 1000; //单位毫秒 _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); _timer.Start(); } private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { Trace.WriteLine("Test System.Timers.Timer"); #region 此处展示的是把副线程的内容转到主线程 System.Windows.Application.Current.Dispatcher.Invoke( new Action(() => { Trace.WriteLine("同步切换"); })); System.Windows.Application.Current.Dispatcher.BeginInvoke( new Action(() => { Trace.WriteLine("异步切换"); })); #endregion _timer.Stop(); } catch (Exception ex) { Trace.WriteLine("Error"); _timer.Stop(); _timer.Start(); } }
System.Threading.Timer:
System.Threading.Timer _timer; private void TeseThreadingTimer() { _timer = new System.Threading.Timer(new System.Threading.TimerCallback(Out), null, 0, 1000); //各参数意思详见:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.timer?redirectedfrom=MSDN&view=netframework-4.8 } private void Out(object sender) { try { Trace.WriteLine("Test System.Threading.Timer"); } catch (Exception ex) { Trace.WriteLine("Error"); } } private void Stop() { _timer.Dispose(); }
此处个人无关记载:Environment.TickCount
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构