articles

Home / DeveloperSection / Articles / Join, Sleep and Interrupt methods in C# Threading

Join, Sleep and Interrupt methods in C# Threading

Anonymous User15439 26-Aug-2014

Previously, we learn about DLL in Creating and Using Dll (Dynamic Link Library) in C#  now we see Join Sleep and Interrupt methods in c# Threading

In this article I’m explaining about how to work thread in c#.

Joining Thread:

The Join method (without any parameters) blocks the calling thread until the current thread is terminated. It should be noted that the caller will block indefinitely if the current thread does not terminate. If the thread has already terminated when the Join method is called, the method returns immediately.

The Join method has an override, which lets you set the number of milliseconds to wait on the thread to finish. If the thread has not finished when the timer expires, join exits and returns control to the calling thread (and the joined thread continues to execute).

This method changes the state of the calling thread to include WaitSleepJoin .

This method is quite useful if one thread depends on another thread.

In this example, we have create two threads I want the thread1 to run first and the

thread2 to run after complete execution of thread1.

using System.Threading;
 
namespace ThreadWorking
{
    class Program
    {
        public static Thread thread1;
        public static Thread thread2;
        static void Main(string[] args)
        {
            thread1 = new Thread(new ThreadStart(FirstThread));
            thread2 = new Thread(new ThreadStart(SecondThread));
            thread1.Name = "First Thread";
            thread2.Name = "Second Thread";
            thread1.Start();
            thread2.Start();
            Console.ReadLine();
        }
        public static void FirstThread()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Thread1 State [{0}] thread1 {1}",thread1.ThreadState,i.ToString());
            }
        }
        public static void SecondThread()
        {
            Console.WriteLine("Thread2 State [{0}] just about to join, Thread1 State [{1}], CurrentThreadName={2}",thread2.ThreadState,thread1.ThreadState,Thread.CurrentThread.Name);
            thread1.Join();
            Console.WriteLine("Thread2 State [{0}] Thread2 just joined Thread1, Thread1 State [{1}], CurrentThreadName={2}",
                thread2.ThreadState, thread1.ThreadState,
                Thread.CurrentThread.Name);
 
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(
                    "Thread2 State [{0}], Thread1 State [{1}], CurrentThread='{2}'  {3}",
                    thread2.ThreadState, thread1.ThreadState,
                    Thread.CurrentThread.Name, i.ToString());
            }
        }
    }
}

 

Output

Join, Sleep and Interrupt methods in C# Threading

 

Sleep:

The static Thread. Sleep () method available on the Thread class is fairly simple it simply suspends the current thread for a specified time. Consider the following example, where two threads are started that run two separate counter methods the first thread (thread1) counts from 0-30, and the second thread (thread2) counts from 31-60.

Thread thread1 will go to sleep for 1 second when it reaches 10, and thread thread2 will go to sleep for 5 seconds when it reaches 45.

using System.Threading;
 
namespace ThreadSleep
{
    class Program
    {
        public static Thread thread1;
        public static Thread thread2;
        static void Main(string[] args)
        {
            thread1 = new Thread(new ThreadStart(FirstThread));
            thread2 = new Thread(new ThreadStart(SecondThread));
            thread1.Start();
            thread2.Start();
            Console.ReadLine();
        }
        public static void FirstThread()
        {
            Console.WriteLine("Enter First Thread");
            for (int i = 0; i <= 30; i++)
            {
                Console.WriteLine(i);
                if (i == 10)
                {
                    Thread.Sleep(1000);
                }
            }
            Console.WriteLine("Exit First Thread");
        }
        public static void SecondThread()
        {
            Console.WriteLine("Enter Second Thread");
            for (int i = 31; i <= 60; i++)
            {
                Console.WriteLine(i);
                if (i == 45)
                {
                    Thread.Sleep(5000);
                }
            }
            Console.WriteLine("Exit Second Thread");
        }
    }
}

Output

Join, Sleep and Interrupt methods in C# Threading

 
Interrupt:

When a thread is put to sleep, the thread goes into the WaitSleepJoin state. If the thread is in this state it may be placed back in the scheduling queue by the use of the Interrupt method. Calling Interrupt when a thread is in the WaitSleepJoin state will cause a ThreadInterruptedException to be thrown any code that is written needs to catch this exception.

using System.Threading;
 
namespace ThreadInterrupt
{
    class Program
    {
        public static Thread sleeperThread;
        public static Thread wakerThread;
        public static void Main(string[] args)
        {
            sleeperThread = new Thread(new ThreadStart(ThreadToSleep));
            wakerThread = new Thread(new ThreadStart(WakeThread));
            sleeperThread.Start();
            wakerThread.Start();
            Console.ReadLine();
        }
        private static void ThreadToSleep()
        {
            for (int i = 0; i < 50; i++)
            {
                Console.Write(i + " ");
                if (i == 10 || i == 20 || i == 30)
                {
                    try
                    {
                        Console.WriteLine("Sleep, Going to sleep at {0} Seconds",i.ToString());
                        Thread.Sleep(20);
                    }
                    catch (ThreadInterruptedException e)
                    {
                        Console.WriteLine("ForceFully ");
                    }
                    Console.WriteLine("woken");
                }
            }
        }
        private static void WakeThread()
        {
            for (int i = 51; i < 100; i++)
            {
                Console.Write(i + " ");
 
                if (sleeperThread.ThreadState == ThreadState.WaitSleepJoin)
                {
                    Console.WriteLine("Interrupting sleeper");
                    sleeperThread.Interrupt();
                }
            }
        }
    }
}

 

Output

Join, Sleep and Interrupt methods in C# Threading


 You  may also want to read: Join, Sleep and Abort methods in C# Threading


In my next post, we are going to learn about : Multithreading in C#


Updated 24-Nov-2019
I am a content writter !

Leave Comment

Comments

Liked By