0

if you run this code below, the event handler is never invoked for global error handler.

static bool exiting = false;

static void Main(string[] args)
{
    try
    {
        System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        demo.Start();
        Console.ReadLine();
        exiting = true;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Caught an exception");
    }
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Console.WriteLine("Notified of a thread exception... application is terminating.");
}

static void DemoThread()
{
    Action x = () => { throw new Exception("this is simple"); };
    x.BeginInvoke(null, null);
}
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
charvind
  • 154
  • 2
  • 9
  • try to look at this example it might help https://stackoverflow.com/questions/5983779/catch-exception-that-is-thrown-in-different-thread – Maytham Fahmi Dec 06 '18 at 04:45

1 Answers1

1

Your problem is the BeginInvoke().

If you used x(); you wouldn't have a problem.

Put simply, if you call a delegate using BeginInvoke(), any exception that is thrown during its execution is handled and then rethrown when you call EndInvoke() however you are using this as a fire and forget (I'm not sure why), and your exception is unobserved as it has nothing to call back to.

Solve?

x.EndInvoke(x.BeginInvoke(null, null));

// or

x();

The call to EndInvoke raises the exception on the caller, and it propagates to AppDomain.CurrentDomain.UnhandledException as you would expect.

However on saying this, this all seems a little suspicious, I think you should ditch trying to call a delegate asynchronously and the Thread class in general, and use tasks and appropriate modern BCL methods and patterns for asynchrony.,


Additional Resources

Delegate Class

If an invoked method throws an exception, the method stops executing, the exception is passed back to the caller of the delegate, and remaining methods in the invocation list are not invoked. Catching the exception in the caller does not alter this behavior.

For documentation Asynchronous patterns and delegates:

Calling Synchronous Methods Asynchronously

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141