I would like to execute a function when the running application terminated via normal close way (right top X) or un expected error happened and software terminated.
How can i do this at c# 4.5 WPF application
Thank you
I would like to execute a function when the running application terminated via normal close way (right top X) or un expected error happened and software terminated.
How can i do this at c# 4.5 WPF application
Thank you
In your App.xaml.cs
-
OnStartUp
method and hook UnhandledException
event of
Current AppDomain
, it will get called whenever application was
about to close because of some unhandled exception.OnExit
method for normal close of application.Create CleanUp
method and call the method from above two methods.
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
private void CleanUp()
{
// Your CleanUp code goes here.
}
protected override void OnExit(ExitEventArgs e)
{
CleanUp();
base.OnExit(e);
}
void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
CleanUp();
}
You could handle the Exit
event of the app's Application
subclass main instance
and the UnhandledException
event of the current AppDomain
instance like so:
public partial class App : Application {
public App() {
this.Exit += App_Exit;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
MessageBox.Show("Exception " + e.ExceptionObject.GetType().Name);
}
void App_Exit(object sender, ExitEventArgs e) {
MessageBox.Show("Bye bye");
}
}
Please note that given the following (simulated by clicking some buttons) scenarios for unhandled exceptions:
which handle their respective click events like so:
private void buttonThrowNice_Click(object sender, RoutedEventArgs e) {
throw new Exception("test");
}
private void buttonStackOverflow_Click(object sender, RoutedEventArgs e) {
this.buttonStackOverflow_Click(sender, e);
}
private void buttonFailFast_Click(object sender, RoutedEventArgs e) {
Environment.FailFast("my fail fast");
}
private void buttonOutOfMemory_Click(object sender, RoutedEventArgs e) {
decimal[,,,,,] gargantuan = new decimal[int.MaxValue,int.MaxValue,int.MaxValue,int.MaxValue, int.MaxValue, int.MaxValue];
Debug.WriteLine("Making sure the compiler doesn't optimize anything: " + gargantuan.ToString());
}
The UnhandledException
event of the AppDomain
class only handles:
OutOfMemoryException
whereas the:
StackOverflow
exceptionare not caught.