1

I'm having troubles with handling exceptions in my application (WPF).

I'm using Tasks a lot, and I would like to have a global exception handler for all exceptions (even inside tasks).

I have tried multiple handlers:

AppDomain.CurrentDomain.UnhandledException
DispatcherUnhandledException 

These works well for exceptions thrown in Application (not within a task)

For exceptions from tasks I tried to use

TaskScheduler.UnobservedTaskException

But this is being ran after a big delay. I think this is because of GarbageCollector, so I found one solution (which does not work too). This solution looks like this:

.ContinueWith(c =>
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        },TaskContinuationOptions.OnlyOnFaulted);

Could you please tell me how I should handle these exceptions? I would like to avoid handling it each time I run a tasks. A global handler is preferred for me.

Tomasz
  • 2,051
  • 3
  • 31
  • 64
  • this might help: http://stackoverflow.com/questions/19164556/how-to-catch-observe-an-unhandled-exception-thrown-from-a-task – null1941 Jan 06 '16 at 12:22
  • I tried this one. The answer does not help me, because a) I cannot use wait/await in this case (this removes asynchronous from my call) b) the custom Scheduler does not work – Tomasz Jan 06 '16 at 12:31
  • I have the same problem did you come up with a solution? – Furkan Gözükara Feb 10 '20 at 12:46

1 Answers1

0

I think you can write a extension class for Task for handling exceptions

 public static class ExtensionClass
    {
        public static void Catch<TException>(this Task task, Action<TException> exceptionHandler,
                                    TaskScheduler scheduler = null) where TException : Exception
        {
            if (exceptionHandler == null)
                throw new ArgumentNullException("exceptionHandler cannot be null");

        }
    }

And you can write all Task.Run like this

 private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            Task.Run((Action)TryExecute).Catch<Exception>((r) => Console.WriteLine("Caught Exception {0}", r));
        }

        private static void TryExecute()
        {
            throw new NotImplementedException();
        }
Justin CI
  • 2,693
  • 1
  • 16
  • 34
  • This will require to add .Catch<> block to every invocation of Task.Run? Is there a way to auto-add it to all invocations? – Tomasz Jan 06 '16 at 14:42