user829174 user829174 - 3 months ago 11
C# Question

How to pass exception explicitly to the main thread in c#

I am familiar with the fact that exception thrown in a thread normally couldn't be caught in another thread.
How can i transfer the error however to the main thread?

public static void Main()
{
new Thread (Go).Start();
}

static void Go()
{
try
{
// ...
throw null; // The NullReferenceException will get caught below
// ...
}
catch (Exception ex)
{
// Typically log the exception, and/or signal another thread
// that we've come unstuck
// ...
}
}

Answer

If you're using .NET 4 there are better ways to do this with Tasks, but assuming you need to use Threads...

If your example is a console app, then your Main method will exit, possibly before Go starts executing. So your "main thread" may not exist when the exception is thrown. To stop this, you need some synchronization.

Something like this should do:

static Exception _ThreadException = null;

public static void Main()
{
    var t = new Thread ( Go );
    t.Start();

    // this blocks this thread until the worker thread completes
    t.Join();

    // now see if there was an exception
    if ( _ThreadException != null ) HandleException( _ThreadException );
}

static void HandleException( Exception ex )
{
    // this will be run on the main thread
}

static void Go()
{
    try
    {
        // ...
        throw null;    // The NullReferenceException will get caught below
        // ...
    }
    catch (Exception ex) 
    {
        _ThreadException = ex;
    }
}

If this is a UI app, things are a bit easier. You will need to pass some reference to your UI thread into the Go method so it knows where to send the exception. The best way to do this is to pass the SynchronizationContext of the UI thread.

Something like this would work:

public static void Main()
{
    var ui = SynchronizationContext.Current;
    new Thread ( () => Go( ui ) ).Start();
}

static void HandleException( Exception ex )
{
    // this will be run on the UI thread
}

static void Go( SynchronizationContext ui )
{
    try
    {
        // ...
        throw null;    // The NullReferenceException will get caught below
        // ...
    }
    catch (Exception ex) 
    {
        ui.Send( state => HandleException( ex ), null );
    }
}
Comments