本文介绍了确保在关闭之前执行C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing an app that need to save the time when computer shutdown, I need to be sure that always computer shutdown/restart, this code executes.

我正在这样的表单关闭事件中编写它:

I'm writing it at Form Closing event like this:

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

通常,代码可以正常工作,并且可以将DateTime保存在设置中,但是我认为有时在保存完成之前关闭了应用程序,并丢失了数据.我不知道应用程序关闭之前有多少时间.

Usually the code is working and it's saving the DateTime in settings, but I think sometimes the app is closed before the saving is done and lost the data. I don´t know how much time has the app before closing when shutdown.

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

¿Is there any way I can be sure that code always finish before shutdown?

谢谢.

推荐答案

您可以将处理程序附加到 SystemEvents.SessionEnded 事件,然后在此处运行代码.您甚至可以使用Cancel属性取消关闭/注销事件.可以在 FormClosing 事件上运行相同的代码,但使用 CloseReason == CloseReason.UserClosing ||CloseReason == CloseReason.ApplicationExitCall ||CloseReason == CloseReason.TaskManagerClosing 涵盖所有情况.

You can attach a handler to the SystemEvents.SessionEnded event and run your code there. You can even cancel the shutdown / logoff event using the Cancel property.The same code could be run on the FormClosing event but with CloseReason == CloseReason.UserClosing || CloseReason == CloseReason.ApplicationExitCall || CloseReason == CloseReason.TaskManagerClosing to cover all scenarios.

这篇关于确保在关闭之前执行C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 21:24