質問

私は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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top