Thursday, April 5, 2012

C# .NET - Catching threadpool thread exceptions

Problem: You receive a compiler error of exception was unhandled when trying to catch exception in a method called by a thread in main thread.



Impact: Developer cannot debug the application and catch the exception from a thread running in main thread. The application will crash if any exception is generated in thread from a thread pool.



Solution: We need to understand why this compiler error is generated when trying to catch exception from a method called by a thread from a thread pool. The answer is simple "They are different threads". Confused???
Ok let us put it this way..
Imagine main method thread as a highway (1) and one road branched out from Highway (1) which is the thread t from thread pool as Highway (2).
* If a car going on highway (1) crashes than the traffic will be blocked and Highway (1) will know about it.
* If a car going on highway (2) crashes than the traffic will be blocked and Highway (2) will know about it.
But how can Highway (2) inform Highway (1) that a car has crashed on Highway (2) unless there is another entry point along the Highway (1) into Highway (2). Both the Highways has there individual traffic which goes on without affecting each other.
The same way an exception thrown on a thread from a thread pool wont be caught by the try - catch block of main thread.
We need to wrap the try - catch block around the thread delegate to make this work and catch the exception thrown.

class Program
    {
        static void Main(string[] args)
        {
            try
        {
            Thread t = new Thread(() =>
                {
                    try
                    {
                        exec();
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine("exception caught");
                        System.Console.ReadLine();

                    }
                }
                );              
            t.Start();

        }
        catch (Exception ex)
        {

        }
    }
    static void exec()
    {
        throw new NullReferenceException();
    }

       
    }

No comments:

Post a Comment