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();
}
No comments:
Post a Comment