我正在开发一个 Web 应用程序,该应用程序运行多个线程,这些线程处理套接字和文件 I/O。所以在应用程序关闭的情况下,我首先要完成这些线程并清理它们。
我已经找到了以下代码,它在正常关机的情况下效果很好。
public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime)
{
applicationLifetime.ApplicationStopping.Register(OnShutdown);
}
private void OnShutdown()
{
// Do your cleanup here
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当您进行非正常关机时,不会调用 OnShutDown() 方法。
在 Forms 中,您可以使用以下代码检测各种关闭原因:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.ApplicationExitCall:
// The Exit method of the Application class was called.
break;
case CloseReason.FormOwnerClosing:
// The owner form is closing.
break;
case CloseReason.MdiFormClosing:
// The parent form is closing.
break;
case CloseReason.None:
// Unknown …Run Code Online (Sandbox Code Playgroud)