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.Exitedevent, 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).”