如何在Environment.Exit()之前调用事件? [英] How to call event before Environment.Exit()?

查看:210
本文介绍了如何在Environment.Exit()之前调用事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a console application in C#. If something goes wrong, I call Environment.Exit() to close my application. I need to disconnect from the server and close some files before the application ends.

在Java中,我可以实现关闭钩子,并通过注册它Runtime.getRuntime()。addShutdownHook()

In Java, I can implement a shutdown hook and register it via Runtime.getRuntime().addShutdownHook(). How can I achieve the same in C#?

推荐答案

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

You can attach an event handler to the current application domain's ProcessExit event:

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

这篇关于如何在Environment.Exit()之前调用事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆