C#でコンソールアプリケーションを使用しています。何か問題が発生した場合は、電話をかけEnvironment.Exit()
てアプリケーションを閉じます。アプリケーションが終了する前に、サーバーから切断していくつかのファイルを閉じる必要があります。
Javaでは、シャットダウンフックを実装し、を介して登録できますRuntime.getRuntime().addShutdownHook()
。どうすればC#で同じことを達成できますか?
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);
}