开发者

How to catch any type of application exit?

I have a WPF application. I have implemented the following function, but no one catches all type of application exits.

public partial class App : Application
{
    protected override void OnExit(ExitEventArgs e)
    {}

    private void Application_Exit(object sender, ExitEventArgs e)
    {}

    private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {}

    private void Application_SessionEnding(object sender, SessionEndingCancelEventArgs e)
    {}
}
  • Is there a generic way to handle application exit?
开发者_如何学编程

For example none of above methods fires when application is forced closed (killed). Each time application closes, I need to unlock some objects in database that is locked by user during application run.


You cannot catch all types of exists unless you are running an observer, separate from your application being surveyed (the "target" application).

The reason being you cannot internally catch application crashes (duh), forced process termination (both internal and external) or anything to that effect.

What you have done is perfectly good.

If you do wish to implement a separate observer application, you can use the .NET Process.Exited event, which is fired whenever a process exists for any reason, including application crashes.

Also, as @Christian has pointed out, you should not try to have a catch-all solution, especially when dealing with critical application crashes (this point is subjective). " When you somehow manage [to recover from an unhandled application error], you're usually doing something wrong or at least may get inaccurate results (e.g. when trying to P/Invoke a minidump creation from your own process)."


You can attach a handler to the AppDomain.ProcessExit event; as far as I can tell, it's the most reliable way to tell when your application is exiting.

This won't be available if you move your app to Silverlight, but as long as you stay within WPF (or any other "full-sized" .NET framework app) this should do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜