Catch ThreadAbortException : Thread Interupt Destroy « Thread « C# / C Sharp






Catch ThreadAbortException

 
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();
    }
}

 








Related examples in the same category

1.Destroying Threads