6

In WinForms I use:

  • System.Windows.Forms.Application.ThreadException
  • System.Windows.Application.UnhandledException

What should I use for non-Winforms multi-threaded application?

Consider the complete code below in C# .NET 4.0:

using System;
using System.Threading.Tasks;

namespace ExceptionFun
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Task.Factory.StartNew(() =>
                {
                    throw new Exception("Oops, someone forgot to add a try/catch block");
                });
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //never executed
            Console.WriteLine("Logging fatal error");
        }
    }
}

I have seen tons of similar questions on stackoverflow, but none contained a satisfactory answer. Most answers are of type: "You should include proper exeption handling in your code" or "Use AppDomain.CurrentDomain.UnhandledException".

Edit: It seems my question was misunderstood, so I have reformulated it and provided a smaller code example.

Eiver
  • 2,594
  • 2
  • 22
  • 36
  • 1
    This looks like a duplicate of http://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application – Jodrell Jul 10 '12 at 11:03
  • 1
    In general a global exception handler should be used to log. You should handle locally if there is somthing sensible you can do about the exception. – Jodrell Jul 10 '12 at 11:05
  • This should work just fine. Of course you don't want to use try/catch, that prevents the UnhandledException event handler from running. You don't have to take care of Die() yourself, it is automatic. – Hans Passant Jul 10 '12 at 13:14
  • The link provided by Jodrell is among many other similar topics on StackOverflow and all of them do not handle exceptions that occur in another thread. – Eiver Jul 10 '12 at 13:53

1 Answers1

0

You don't need any equivalents, the CurrentDomain.UnhandledException event is working just fine in multi-threaded console applications. But it is not firing in your case because of the way you start your thread. The handler in your question will not execute in both Windows and Console applications. But if you start your thread like this (for example):

new Thread(() => { 
     throw new Exception("Oops, someone forgot to add a try/catch block"); 
}).Start();

It'll fire.

The Task.Factory.StartNew(...) and CurrentDomain.UnhandledException problem is discuessed in many posts on SO. Check some suggestions here:

How to handle all unhandled exceptions when using Task Parallel Library?

What is the best way to catch exception in Task?

Community
  • 1
  • 1
Ahmad Ibrahim
  • 1,915
  • 2
  • 15
  • 32