In-Depth Reference to Suspension of Thread in C#

In this tutorial, you will learn how to suspend the Current thread for a particular amount of time in C#. (C sharp)

What is Thread Suspension in C#?

A thread is an independent stream of instruction in a program used to execute the logic of an application. “Thread Suspension” in an application or program acts like a pause button. It is similar to; when you are playing a game for a long time and now want some rest OR while doing some work suddenly asking someone for help due to an emergency and now you are waiting for him/her. For example, in the application what happens if your Database isn’t responding then your thread must wait until and unless your database responds.

    Methods of suspending Threads: –

    • Thread.Sleep() Method: Imagine you’re coding and need to introduce a delay. The Thread.Sleep() method comes to the rescue.
    • ManualResetEvent: Another trick up your sleeve is using the ManualResetEvent class. It’s like a traffic light for threads – when it’s red, the thread waits patiently; when it turns green, off it goes.

Here is the implementation using Thread.Sleep() method,

Example 1:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine("Main thread started.");
        Console.WriteLine("Main thread going to deactivate for 2 seconds");
        
        Thread.Sleep(2000);// Suspend the main thread for 2 seconds
        
        Console.WriteLine("Main thread resumed.");
    }
}

Output:

Main thread started.
Main thread going to deactivate for 2 seconds
Main thread resumed.

Example 2:

Creation of child threads and executing them,

using System;
using System.Threading;

namespace threadingclass
{
    internal class Program
    {
        static void test1()
        {
            if (10 % 2 == 0)
            {
                Console.WriteLine("test1, current thread is going to sleep for 3 seconds");
                Thread.Sleep(3000);
                Console.WriteLine("test1, woke up");
                Console.WriteLine("10 is an even number.");
            }
        }

        static void test2()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("test2, current thread is going to sleep for 2 seconds");
                Thread.Sleep(1000);
                Console.WriteLine("test2, woke up");
                Console.WriteLine("test-2 " + i);
            }
        }

        static void test3()
        {
            for (int i = 10; i < 20; i++)
            {
                Console.WriteLine("test-3 " + i);
                if (i == 15)
                {
                    Console.WriteLine("test3, current thread is going to sleep for 2 seconds");
                    Thread.Sleep(2000);
                    Console.WriteLine("test3, woke up");
                }
            }
        }

        static void Main(string[] args)
        {
            Thread T1 = new Thread(test1);
            Thread T2 = new Thread(test2);
            Thread T3 = new Thread(test3);
            T1.Start();
            T2.Start();
            T3.Start();
            Console.ReadLine();
        }
    }
}

Output:

test1, current thread is going to sleep for 3 seconds
test2, current thread is going to sleep for 2 seconds
test-3 10
test-3 11
test-3 12
test-3 13
test-3 14
test3, current thread is going to sleep for 2 seconds
test-3 15
test3, woke up
test-3 16
test-3 17
test-3 18
test-3 19
test2, woke up
test-2 0
test2, current thread is going to sleep for 2 seconds
test-2 1
test2, woke up
test-2 2
test2, current thread is going to sleep for 2 seconds
test-2 3
test2, woke up
test-2 4
test2, current thread is going to sleep for 2 seconds
test-2 5
test2, woke up
test-2 6
test2, current thread is going to sleep for 2 seconds
test-2 7
test2, woke up
test-2 8
test2, current thread is going to sleep for 2 seconds
test-2 9
test2, woke up
test1, woke up
10 is an even number.

Explanation:

  • test1 Function:
    • It checks if  10 % 2 equals zero (which it does since 10 is an even number).
    • If it is true, it will print the following messages:
      • “test1, current thread is going to sleep for 3 seconds”
      • Sleeps for 3 seconds.
      • “test1, woke up”
      • “10 is an even number.”
  • test2 Function:
    • Iterates from 0 to 9.
    • For each iteration:-
      • it will print the following messages:-
        • “test2, current thread is going to sleep for 2 seconds”
        • Sleeps for 2 seconds.
        • “test2, woke up”
        • Displays the value of i (e.g., “test-2 0”, “test-2 1”, …).
  • test3 Function:
    • Iterates from 10 to 19.
    • For each iteration:-
      • Prints the value of i.
      • If i equals 15, then:-
        • it will print the following messages:-
          • “test3, current thread is going to sleep for 2 seconds”
          • Sleeps for 2 seconds.
          • “test3, woke up”
  • Main Function:
    • Creates three threads (T1, T2, and T3) corresponding to the three test functions.
    • Starts all three threads.
    • Waits for user input (pressing Enter) to keep the program running.
  • This output will always be a mix of messages from the three threads, with delays due to the sleep times. The exact order of messages may vary depending on thread scheduling.

Conclusion:

Don’t try to make your threads dizzy by suspending them in tight loops. It’s like asking someone to stop and start running repeatedly which is not very efficient. By mastering this technique, you’re better equipped to manage concurrency and optimize resource utilization in your C# applications. The more you practice the more you become stronger, so come with us and practice and get yourself in a better place.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top