如何Environment.Exit之前调用事件()?
-
12-09-2019 - |
题
我在C#控制台应用程序。如果出现问题,我呼吁Environment.Exit()
关闭我的申请。我需要应用程序结束之前,从服务器断开连接,并关闭一些文件。
在Java中,我可以实现关闭挂钩和经由Runtime.getRuntime().addShutdownHook()
注册它。我怎样才能达到同样的在C#?
解决方案
您可以将一个事件处理程序的当前应用程序域的ProcessExit事件:
using System;
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
Environment.Exit(0);
}
}
其他提示
的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)
{
}
我建议包装在您自己的方法调用Environment.Exit()和使用,在整个。是这样的:
internal static void MyExit(int exitCode){
// disconnect from network streams
// ensure file connections are disposed
// etc.
Environment.Exit(exitCode);
}
不隶属于 StackOverflow