请确保 C# 代码在关机前执行



我正在开发一个应用程序,需要节省计算机关机时的时间,我需要确保始终计算机关机/重新启动,执行此代码。

我在表单关闭活动中写的,如下所示:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{         
if(e.CloseReason == CloseReason.WindowsShutDown)
{
Properties.Settings.Default.lastShutdown = DateTime.Now;
Properties.Settings.Default.Save();
}
}

通常代码可以正常工作,它会在设置中保存日期时间,但我认为有时应用程序在保存完成之前就关闭并丢失了数据。我不知道应用程序在关机时关闭之前有多少时间。

¿有什么方法可以确保代码始终在关闭之前完成?

谢谢。

您可以将处理程序附加到 SystemEvents.SessionEnd 事件并在那里运行代码。您甚至可以使用 Cancel 属性取消关机/注销事件。 可以在FormClosing事件上运行相同的代码,但CloseReason == CloseReason.UserClosing || CloseReason == CloseReason.ApplicationExitCall || CloseReason == CloseReason.TaskManagerClosing涵盖所有方案。

您可以定期保存每个会话的最后一次活动时间。 例如,在表单上创建一个计时器。这样,即使你立即失去力量,你也会知道你最后一次活着的时间。

private void Form1_Load(object sender, EventArgs e)
{
/* Set the last shutdown to the last time we were alive.. */
Properties.Settings.Default.LastShutdown = Properties.Settings.Default.LastHeartbeat;
this.timer1.Interval = 100;
this.timer1.Tick += timer1_Tick;
this.timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Properties.Settings.Default.LastHeartbeat = DateTime.UtcNow;
Properties.Settings.Default.Save();
}

我认为如果您定期保存变量会更好,而不是节省"喊叫时间"。这样,如果出现问题,您最多损失 1 个间隔。

只需使用计时器保存整个时间,当计算机关闭并重新启动时,您调用配置中的最后一个条目。

`Timer time = new Timer(1);
time.Elapsed += timer_elapsed();
private static void timer_elapsed(Object source, System.Timers.ElapsedEventArgs e) { YOUR CODE HERE}`

最新更新