muhammet talha ┼čahin muhammet talha ┼čahin - 1 year ago 187
C# Question

Handling Unhandled Exception in WPF

I'm trying to handle any unhandled exception thrown in the application using this:

The xaml:

<Application x:Class="Updater.App"

The code:

private void UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
var time = DateTime.Now;
File.AppendAllText(@"C:\exps.csv", string.Format("{0},{1}", time, e.Exception.Message));
File.AppendAllText(@"C:\sts.txt", time + ":\n" + e.Exception.StackTrace + "\n");
e.Handled = false; //we want the user to experience the crash

But the dispatcher not working and not execute when the application throw exception.

Answer Source

I think your problem is that you are using Dispatcher.UnhandledException who trap unhandled exceptions from a single specific UI dispatcher thread.

Try usingAppDomain.UnhandledException who trap unhandled exceptions from all threads in the AppDomain.

Genrelly (source):

  1. AppDomain.UnhandledException From all threads in the AppDomain.
  2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  3. Application.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  4. TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download