2009-12-03 5 views
7

C#에서 콘솔 응용 프로그램이 있습니다. 문제가 발생하면 Environment.Exit()으로 전화하여 신청서를 닫습니다. 응용 프로그램이 종료되기 전에 서버에서 연결을 끊고 일부 파일을 닫아야합니다.Environment.Exit() 전에 이벤트를 호출하는 방법?

자바에서는 종료 훅을 구현하고 Runtime.getRuntime().addShutdownHook()을 통해 등록 할 수 있습니다. 어떻게하면 C#에서 같은 결과를 얻을 수 있습니까?

답변

18

:

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

나는 람다를 좋아하지 않는다 :). 하지만 고마워, 아프다. – Makah

-2

Environment.Exit()에 대한 호출을 자신의 메서드에서 랩핑하고 그 전역을 사용하는 것이 좋습니다. 이런 식으로 뭔가 : 당신은 현재 응용 프로그램 도메인의 ProcessExit 이벤트에 이벤트 핸들러를 첨부 할 수 있습니다

internal static void MyExit(int exitCode){ 
    // disconnect from network streams 
    // ensure file connections are disposed 
    // etc. 
    Environment.Exit(exitCode); 
} 
+0

C#을 종료에 존재하지 않습니다 행사? – Makah

+1

-1 :이 기능을 사용하지 않고 다른 작업을 수행 할 수있는 다른 쉬운 방법이있는 경우 Coupling이 크게 증가합니다. http://en.wikipedia.org/wiki/Coupling_(computer_science) –

+0

커플 링이 어떻게 증가합니까? 문제는 Console 응용 프로그램 내에서이 문제를 해결하는 방법에 대해 묻는 것입니다. 따라서 Environment.Exit을 호출하면 유효한 동작이됩니다. 이벤트를 사용하면 쉽게 사용할 수 있지만 프로세스가 아니라 AppDomain을 사용합니다. –

9

후크 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) 
{ 
} 
관련 문제