如何使用.NET Timer类在特定时间触发事件?

编程入门 行业动态 更新时间:2024-10-09 09:20:26
本文介绍了如何使用.NET Timer类在特定时间触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在我的应用程序时在一定的时间之日其连续运行触发的事件,称下午4:00。我想过运行计时器每一秒,当时间等于下午4:00运行事件。这样可行。但我不知道是否有一种方法在下午4:00到刚刚拿到回调一次,不必继续检查。

I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and when the time is equal to 4:00pm run the event. That works. But I'm wondering if there's a way to just get the callback once at 4:00pm and not having to keep checking.

推荐答案

如何这样的事情,使用System.Threading.Timer上课吗?

How about something like this, using the System.Threading.Timer class?

var t = new Timer(TimerCallback); // Figure how much time until 4:00 DateTime now = DateTime.Now; DateTime fourOClock = DateTime.Today.AddHours(16.0); // If it's already past 4:00, wait until 4:00 tomorrow if (now > fourOClock) { fourOClock = fourOClock.AddDays(1.0); } int msUntilFour = (int)((fourOClock - now).TotalMilliseconds); // Set the timer to elapse only once, at 4:00. t.Change(msUntilFour, Timeout.Infinite);

请注意,如果您使用 System.Threading.Timer ,由 TimerCallback 指定的回调将被执行的一个线程池(非UI)线程,所以如果你在4:00做你的UI策划的东西,你就会有code恰当(例如,使用元帅控制.Invoke 在Windows窗体应用程序,或 Dispatcher.Invoke 在一个WPF应用程序)。

Note that if you use a System.Threading.Timer, the callback specified by TimerCallback will be executed on a thread pool (non-UI) thread—so if you're planning on doing something with your UI at 4:00, you'll have to marshal the code appropriately (e.g., using Control.Invoke in a Windows Forms app, or Dispatcher.Invoke in a WPF app).

更多推荐

如何使用.NET Timer类在特定时间触发事件?

本文发布于:2023-11-27 14:28:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638455.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   事件   时间   在特定   Timer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!