11

我在 C# 中有一个控制台应用程序。如果出现问题,我会打电话Environment.Exit()关闭我的应用程序。我需要在应用程序结束之前断开与服务器的连接并关闭一些文件。

在 Java 中,我可以实现一个关闭挂钩并通过Runtime.getRuntime().addShutdownHook(). 如何在 C# 中实现相同的目标?

4

3 回答 3

29

您可以将事件处理程序附加到当前应用程序域的 ProcessExit 事件:

using System;
class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
        Environment.Exit(0);
    }
}
于 2009-12-03T19:07:52.883 回答
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)
{
}
于 2009-12-03T19:09:48.220 回答
-2

我建议将对 Environment.Exit() 的调用包装在您自己的方法中并在整个过程中使用它。像这样的东西:

internal static void MyExit(int exitCode){
    // disconnect from network streams
    // ensure file connections are disposed
    // etc.
    Environment.Exit(exitCode);
}
于 2009-12-03T19:00:59.450 回答