C Sharp

Managing Thread Lifetimes

There are many different tasks you might need to perform to manage the activity or life of a thread. You can manage all these tasks by using the different Thread methods. For example, it's quite common to need to pause a thread for a given period of time. To do this, you can call the Thread.Sleep method. This method takes a single argument that represents the amount of time, in milliseconds, that you want the thread to pause. Note that the Thread.Sleep method is a static method and cannot be called with an instance of a Thread object. There's a very good reason for this. You're not allowed to call Thread.Sleep on any other thread except the currently executing one. The static Thread.Sleep method calls the static CurrentThread method, which then pauses that thread for the specified amount of time. Here's an example: -

using System;
using System.Threading;
class ThreadSleepApp
{
    public static void WorkerThreadMethod()
    {
        Console.WriteLine("Worker thread started");
        int sleepTime = 5000;
        Console.WriteLine("\tsleeping for {0} seconds", sleepTime / 1000);
        Thread.Sleep(sleepTime); // Sleep for five seconds.
        Console.WriteLine("\twaking up");
    }
    public static void Main()
    {
        ThreadStart worker = new ThreadStart(WorkerThreadMethod);
        Console.WriteLine("Main - Creating worker thread");
        Thread t = new Thread(worker);
        t.Start();
        Console.WriteLine
            ("Main - Have requested the start of worker thread");
    }
}

There are two more ways to call the Thread.Sleep method. First, by calling Thread.Sleep with the value 0, you'll cause the current thread to relinquish the unused balance of its timeslice. Passing a value of Timeout.Infinite results in the thread being paused indefinitely until the suspension is interrupted by another thread calling the suspended thread's Thread.Interrupt method.

The second way to suspend the execution of a thread is by using the Thread.Suspend method. There are some major difference between the two techniques. First, the Thread.Suspend method can be called on the currently executing thread or another thread. Second, once a thread is suspended in this fashion, only another thread can cause its resumption, with the Thread.Resume method. Note that once a thread suspends another thread, the first thread is not blocked. The call returns immediately. Also, regardless of how many times the Thread.Suspend method is called for a given thread, a single call to Thread.Resume will cause the thread to resume execution.