Know When a Thread Finishes - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Know When a Thread Finishes

Demo Code


using System;//from   w w  w  .  j a  va  2  s  .com
using System.Threading;

class MainClass
    {
        private static void DisplayMessage()
        {
            for (int count = 0; count < 5; count++)
            {
                Console.WriteLine("{0} : DisplayMessage thread", DateTime.Now.ToString("HH:mm:ss.ffff"));

                // Sleep for 1 second.
                Thread.Sleep(1000);
            }
        }

        public static void Main()
        {
            Thread thread = new Thread(DisplayMessage);

            Console.WriteLine("{0} : Starting DisplayMessage thread.", DateTime.Now.ToString("HH:mm:ss.ffff"));

            thread.Start();

            if (!thread.Join(2000))
            {
                Console.WriteLine("{0} : Join timed out !!", DateTime.Now.ToString("HH:mm:ss.ffff"));
            }
            Console.WriteLine("Thread alive: {0}", thread.IsAlive);

            thread.Join();

            Console.WriteLine("Thread alive: {0}", thread.IsAlive);

        }
    }

Result


Related Tutorials