Terminate the Execution of a Thread - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Terminate the Execution of a Thread

Demo Code


using System;/*from   w  w  w  .  ja  v  a2s .c om*/
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();
            Console.WriteLine("Sleep 5 seconds");
            Thread.Sleep(5000);

            thread.Join();
        }
    }

Result


Related Tutorials