2012-04-11 129 views

回答

5

這樣做的最簡單方法可能是處理AppDomain.ProcessExit event,這是在應用程序的父進程退出時引發的。

例如:

Module MyApp 

    Sub Main() 
     ' Attach the event handler method 
     AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf MyApp_ProcessExit 

     ' Do something 
     ' ... 

     Environment.Exit(0) 
    End Sub 

    Private Sub MyApp_ProcessExit(sender As Object, e As EventArgs) 
     Console.WriteLine("App Is Exiting...") 
    End Sub 

End Module 

但調用Environment.Exit可能不是你原來的問題的最佳解決方案。一般來說,the only time it is necessary to use this method is when there might be other foreground threads running。在這種情況下,值得研究如何優雅地終止其他線程,而不採取嚴厲的措施來殺死整個過程。

Environment.Exit,儘管名稱有些令人愉悅,但卻是一種非常殘忍的舉動。它不像在Windows任務管理器中單擊「結束任務」一樣糟糕(並且請注意,如果您的操作是,那麼ProcessExit事件將不會被提升,這意味着上述建議將不起作用),但它可能不是你真正想要的解決方案。

相關問題