I am completely puzzled. I was so sure that .NET shuts the whole application domain if there is uncaught exception in a thread that I never tested this.
However I just tried the following code and it doesn’t fail… Could anyone please explain why?
(Tried in .NET 4 and 3.5)
static void Main(string[] args)
{
Console.WriteLine("Main thread {0}", Thread.CurrentThread.ManagedThreadId);
Action a = new Action(() =>
{
Console.WriteLine("Background thread {0}", Thread.CurrentThread.ManagedThreadId);
throw new ApplicationException("test exception");
});
a.BeginInvoke(null, null);
Console.ReadLine();
}
This is happening because the
BeginInvokeusesThreadPoolinternally and whenThreadPoolany unhadled exceptions will be silence fail. However if you usea.EndInvokethen the unhadled exception will be throw at theEndInvokemethod.Note: as
João Angelostated that usingThreadPoolmethods directly “likeThreadPool.QueueUserWorkItemsandUnsafeQueueUserWorkItem” will throw exceptions at 2.0 and above.