Exception handling in Multi Threaded application

How do you handle exceptions in the Multi-Threaded application?
The caller (say main method) does not aware what happened in the thread that spanned. Let's see an example.



namespace My_Samples
{
using System.Threading;
using System;

class Program
{
static void Main(string[] args)
{
try
{
Thread t1 = new Thread(MyMethod);
t1.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Main Method...");
Console.ReadLine();
}

static void MyMethod()
{
throw new Exception("Oooooooops Error...");
}
}
}


When you run this code, you never see the exception is handled and you never reach the Catch block in the main method. The reason is each thread has its own execution path. So you never caught the exception. There are 2 ways to handle this.

Method 1 - Move your exception handling from the main method to the thread method.



namespace My_Samples
{
using System.Threading;
using System;

class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(MyMethod);
t1.Start();
Console.WriteLine("Main Method...");
Console.ReadLine();
}

static void MyMethod()
{
try
{
throw new Exception("Oooooooops Error...");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}


Method 2 - Subscribe to Application.ThreadException in Winform or AppDomain.CurrentDomain.UnhandledException in Console Application.
This will handle all the thread exception which are not handled by the threads.



namespace My_Samples
{
using System.Threading;
using System;

class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Thread t1 = new Thread(MyMethod);
t1.Start();
Console.WriteLine("Main Method...");
Console.ReadLine();
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
System.Environment.Exit(0);
}

static void MyMethod()
{
throw new Exception("Oooooooops Error...");
}
}
}


Note - You have to make sure that any unhandled exception should shutdown the application (or System.Environment.Exit).

No comments:

Post a Comment