如何在 Environment.Exit() 之前调用事件?

12

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

在Java中,我可以通过实现一个关闭挂钩并通过Runtime.getRuntime().addShutdownHook()注册它来实现。那么我该如何在C#中实现相同的功能呢?

3个回答

31

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

using System;
class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += (s, e) => Console.WriteLine("Process exiting");
        Environment.Exit(0);
    }
}

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)
{
}

-1
我建议您将对 Environment.Exit() 的调用封装在自己的方法中,并在整个代码中使用该方法。可以像这样实现:
internal static void MyExit(int exitCode){
    // disconnect from network streams
    // ensure file connections are disposed
    // etc.
    Environment.Exit(exitCode);
}

2
-1:当有其他简单的方法可以使事情正常工作时,这显着增加了耦合度,参见:http://en.wikipedia.org/wiki/Coupling_(computer_science)。 - Sam Harwell
如何增加耦合性?该问题是关于如何在控制台应用程序中解决此问题的,因此调用Environment.Exit将是一种有效的操作。尽管使用事件会更容易,但它们会违反AppDomain而不是进程。 - Agent_9191
1
如果您需要在使用完资源A后进行一些清理工作,请将清理工作局限于A。不要要求A、B、C和D做出特殊的适应。 - Sam Harwell
1
有一种情况可能不适用,那就是未处理的异常会导致应用程序退出,在这种情况下 MyExit 不会被调用。但仍然是一个有效的答案。不认为这应该被投反对票。 - nawfal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接