Environment.exit () 전에 이벤트를 호출하는 방법?
-
12-09-2019 - |
문제
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)
{
}
나는 자신의 방법으로 환경에 전화를 래핑하고 그 전체에 걸쳐 사용하는 것이 좋습니다. 이 같은:
internal static void MyExit(int exitCode){
// disconnect from network streams
// ensure file connections are disposed
// etc.
Environment.Exit(exitCode);
}
제휴하지 않습니다 StackOverflow