Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions in multithreaded application.

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 something like this but couldn't catch the exception in the creating thread.

    static void Main(string[] args)
    {
        ParameterizedThreadStart pts = 
           new ParameterizedThreadStart(ThreadMethod);
        try
        {
            Thread t = new Thread(pts);
            t.Start(new object());
            Console.ReadLine();
        }
        catch (Exception ex) //the exception is not caught
        {
            Debugger.Break();
        }
    }


    static void ThreadMethod(object @object)
    {
        Thread.Sleep(2000);
        throw new IndexOutOfRangeException();
        Thread.CurrentThread.Abort();
    }
like image 559
Func Avatar asked Apr 06 '11 16:04

Func


2 Answers

The thread's exception will not propogate to the main thread's context. This really makes sense - by the time the exception is thrown, the main thread will typically be in a completely different scope than the one containing your exception handler.

You can catch these exceptions (typically to log them) by hooking into AppDomain.UnhandledException. See that page for details, including differences in Windows Forms applications, etc.

like image 179
Reed Copsey Avatar answered Nov 10 '22 20:11

Reed Copsey


This is a great article about Threading in C# and how to handle Exceptions

like image 3
Bek Raupov Avatar answered Nov 10 '22 20:11

Bek Raupov