Mak*_*kah 11 .net c# console-application application-shutdown
我在C#中有一个控制台应用程序.如果出现问题,我打电话Environment.Exit()关闭我的申请.在应用程序结束之前,我需要断开与服务器的连接并关闭一些文件.
在Java中,我可以实现一个关闭钩子并通过它注册它Runtime.getRuntime().addShutdownHook().如何在C#中实现相同的目标?
dri*_*iis 26
您可以将事件处理程序附加到当前应用程序域的ProcessExit事件:
using System;
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
Environment.Exit(0);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 12
钩子AppDomain事件:
private static void Main(string[] args)
{
var domain = AppDomain.CurrentDomain;
domain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
domain.ProcessExit += new EventHandler(domain_ProcessExit);
domain.DomainUnload += new EventHandler(domain_DomainUnload);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("MyHandler caught: " + e.Message);
}
static void domain_ProcessExit(object sender, EventArgs e)
{
}
static void domain_DomainUnload(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)