All about multithreading.

Wednesday, September 5, 2007

Exception Handling in multithreading

Exceptions occurred in threads will not be caught by global exception handler (implemented at program.cs). These exceptions will take the application down. In the following code snippet, the exception thrown by a thread will take the entire application down. 

// ThreadExceptionForm.cs
private void buttonThreadEx_Click(object sender, EventArgs e)
{
Thread t = new Thread(
delegate()
{
// this Exception will take this application down!
//
throw new Exception("New exception from child thread");
}
);
t.Start();
}

private void buttonEx_Click(object sender, EventArgs e)
{
// This will be caught at global Exception handler
//
throw new Exception("New exception from main thread.");
}


// program.cs
// Global exception handling
//
static void Main()
{
Application.EnableVisualStyles();
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ThreadExceptionForm());
}

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "We caught this one");
}




To avoid this, always surround the thread code with try\catch.

private void buttonThreadTryCatchEx_Click(object sender, EventArgs e)
{
Thread t = new Thread(
delegate()
{
try
{
// this Exception will take this application down!
//
throw new Exception("New exception from child thread");

}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "This was caught at thread's try/catch");
}
}
);
t.Start();
}
download the source code.
 

Blog Archive

About Me

One of my friends said "if you want to learn something, write a book about it". I wanted to learn all about multithreading and instead of writing a book, I am trying to blog. Thank you for stopping. I appreciate your feedback. Sreekanth