Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exception in the main thread if the exception occurs in the secondary thread?

How to catch exception in the main thread if the exception occurs in the secondary thread?

The code snippet for the scenario is given below:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        Thread th1 = new Thread(new ThreadStart(Test));
        th1.Start();               
    }
    catch (Exception)
    { 

    }
}

void Test()
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(100);

        if (i == 2)
            throw new MyException();
    }
}
like image 817
Ashish Ashu Avatar asked Jun 01 '10 05:06

Ashish Ashu


2 Answers

You can add a Application.ThreadException Event handler:

Joe is correct. Given the above windows forms code I was assuming Windows forms:

This event allows your Windows Forms application to handle otherwise unhandled exceptions that occur in Windows Forms threads. Attach your event handlers to the ThreadException event to deal with these exceptions, which will leave your application in an unknown state. Where possible, exceptions should be handled by a structured exception handling block.

See Unexpected Errors in Managed Applications

like image 127
Mitch Wheat Avatar answered Oct 12 '22 23:10

Mitch Wheat


Use a BackgroundWorker.

A BackgroundWorker provides the infrastructure for communicating between the main UI thread and a background worker thread, including reporting exceptions. It is almost always a better solution than starting a thread from a button_click event handler.

like image 33
Joe Avatar answered Oct 13 '22 00:10

Joe