Catch ThreadAbortException

image_pdfimage_print
   
 
using System;
using System.Threading;

class MainClass
{
    private static void DisplayMessage()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("{0} : DisplayMessage thread active", DateTime.Now.ToString("HH:mm:ss.ffff"));
                Thread.Sleep(1000);
            }
        }
        catch (ThreadAbortException ex)
        {
            Console.WriteLine("{0} : DisplayMessage thread terminating - {1}",
               DateTime.Now.ToString("HH:mm:ss.ffff"),
              (string)ex.ExceptionState);
        }
        Console.WriteLine("{0} : nothing is called after the catch block",
            DateTime.Now.ToString("HH:mm:ss.ffff"));
    }

    public static void Main()
    {
        Thread thread = new Thread(DisplayMessage);
        Console.WriteLine("{0} : Starting DisplayMessage thread" +
            " - press Enter to terminate.",
            DateTime.Now.ToString("HH:mm:ss.ffff"));
        thread.Start();

        System.Console.ReadLine();
        thread.Abort("User pressed Enter");
        thread.Join();
    }
}

    


This entry was posted in Thread. Bookmark the permalink.