I have heard from a very discerning person that an exception being thrown (and not caught) in a thread is being propagated to the parent thread. Is that true? I have tried some
A decent resource on Threading in C# that has a section for exception handling: Threading in C#
In short, no it doesn't. You have a couple of obvious options:#
This is a great article about Threading in C# and how to handle Exceptions
Exception propagate upwards in the call-stack.
If you start a new thread from a certain method, it will propagate upwards until it gets to that method.
If that method doesn't catch it, you'll get a runtime error that there's an uncaught exception.
An exception can only be caught on the thread from which is came. So throwing an exception on another thread won't cause another thread to catch it.
There is no concept of a "parent" thread.
There is a very simple solution for the special case when the main thread waits for the completion of the other thread (see https://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx#Examples). It requires only a class exception variable.
The modified code sample completed by an exception handler may look like this.
using System;
using System.Threading;
class WaitOne
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static Exception SavedException = null;
static void Main()
{
Console.WriteLine("Main starting.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
autoEvent.WaitOne();
if (SavedException != null)
{
// handle this exception as you want
}
Console.WriteLine("Work method signaled.\nMain ending.");
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
try
{
Thread.Sleep(new Random().Next(100, 2000));
throw new Exception("Test exception");
}
catch (Exception ex)
{
SavedException = ex;
}
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)stateInfo).Set();
}
}