定时器关闭应用程序

如何制作一个计时器,强制应用程序在C#中的指定时间关闭? 我有这样的事情:

void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (++counter == 120) this.Close(); } 

但在这种情况下,应用程序将在计时器运行后的120秒内关闭。 我需要一个计时器,它将关闭应用程序,例如23:00:00。 有什么建议?

您必须解决的第一个问题是System.Timers.Timer将无法正常工作。 它在线程池线程上运行Elapsed事件处理程序,这样的线程无法调用Form或Window的Close方法。 简单的解决方法是使用同步计时器,System.Windows.Forms.Timer或DispatcherTimer,从问题中应用哪个不清楚。

您唯一需要做的就是计算计时器的Interval属性值。 这是相当简单的DateTime算法。 如果你总是希望窗口在晚上11点关闭,那么写下这样的代码:

  public Form1() { InitializeComponent(); DateTime now = DateTime.Now; // avoid race DateTime when = new DateTime(now.Year, now.Month, now.Day, 23, 0, 0); if (now > when) when = when.AddDays(1); timer1.Interval = (int)((when - now).TotalMilliseconds); timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { this.Close(); } 

我假设你在这里谈论Windows Forms。 然后这可能会工作( 编辑更改代码所以this.Invoke使用,因为我们在这里讨论multithreading计时器):

 void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (DateTime.Now.Hour >= 23) this.Invoke((Action)delegate() { Close(); }); } 

如果切换到使用Windows窗体Timer ,则此代码将按预期工作:

 void myTimer_Elapsed(object sender, EventArgs e) { if (DateTime.Now.Hour >= 23) Close(); } 

如果我理解你的要求,让计时器检查每秒的时间似乎有点浪费,你可以做这样的事情:

 void Main() { //If the calling context is important (for example in GUI applications) //you'd might want to save the Synchronization Context //for example: context = SynchronizationContext.Current //and use if in the lambda below eg s => context.Post(s => this.Close(), null) var timer = new System.Threading.Timer( s => this.Close(), null, CalcMsToHour(23, 00, 00), Timeout.Infinite); } int CalcMsToHour(int hour, int minute, int second) { var now = DateTime.Now; var due = new DateTime(now.Year, now.Month, now.Day, hour, minute, second); if (now > due) due.AddDays(1); var ms = (due - now).TotalMilliseconds; return (int)ms; } 

您可能希望获得当前系统时间。 然后,查看当前时间是否与您希望应用程序关闭的时间相匹配。 这可以使用代表即时的DateTime来完成。

 public Form1() { InitializeComponent(); Timer timer1 = new Timer(); //Initialize a new Timer of name timer1 timer1.Tick += new EventHandler(timer1_Tick); //Link the Tick event with timer1_Tick timer1.Start(); //Start the timer } private void timer1_Tick(object sender, EventArgs e) { if (DateTime.Now.Hour == 23 && DateTime.Now.Minute == 00 && DateTime.Now.Second == 00) //Continue if the current time is 23:00:00 { Application.Exit(); //Close the whole application //this.Close(); //Close this form only } } 

谢谢,
我希望你觉得这有用 :)

 void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (DateTime.Now.Hour >= 23) { this.Close(); } } 
 Task.Delay(9000).ContinueWith(_ => { this.Dispatcher.Invoke((Action)(() => { this.Close(); })); } ); 

将您的计时器设置为像现在一样检查每一秒,但是将内容交换为:

 void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (DateTime.Now.Hour == 23) this.Close(); } 

这将确保当计时器运行且时钟为23:xx时,应用程序将关闭。