Sunday, August 7, 2016

How to pass exception form child thread to parent thread


We can pass exception from child thread to parent thread with the help of delegate. we have to pass delegate in thread method and we will invoke delegate when any error occurred in child thread.
parent thread subscribes delegate so corresponding method will be invoked by delegate from child thread.
see below example:

using System.Threading.Tasks;
using System.Windows.Forms;
namespace GuruCSharpConsole.Threads
{
    public delegate void ErrorHandler(string errorMessage);
 //instead of string as input param we can also use Exception type as input param in delegate to get complete //exception details.
 
    class PassExceptionToMainThread
    {
       public static ErrorHandler errorHandler;

        public static void Main()
        {
            errorHandler += new ErrorHandler(ShowErrorMessage);

            for (int i = 0; i < 50; i++)
            {
                Thread t = new Thread(() => { DivideByZero(5, 0, errorHandler); }); //Passing delegate to each thread.
                t.Start();
             
            }
            Console.Read();
        }

        public static void DivideByZero(int a, int b,ErrorHandler eHandler)
        {
            try
            {
                double r = a / b;
                Console.WriteLine(" Result from thread {0} ={1}", Thread.CurrentThread.ManagedThreadId, r);
            }
            catch (Exception ex)
            {
                if (eHandler != null)
                {
                    eHandler("Thread=" + Thread.CurrentThread.ManagedThreadId + ex.Message);
                }
            }
        }

        public static void ShowErrorMessage(string err)
        {
            MessageBox.Show(err);
        }
    }
}

in the above example I am using System.Windows.Forms namespace to use "MessageBox" in console application otherwise it's not needed. 

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...