Subscribe

RSS Feed (xml)

How To Know When a Thread Finishes

The easiest way to test if a thread has finished executing is to test the Thread.IsAlive property. The IsAlive property returns true if the thread has been started but has not terminated or been aborted.
Commonly, you will need one thread to wait for another thread to complete its processing. Instead of testing IsAlive in a loop, you can use the Thread.Join method. Join causes the calling thread to block until the referenced thread terminates, at which point the calling thread will continue. You can optionally specify an int or a TimeSpan value that specifies the time after which the Join operation will time out and execution of the calling thread will resume. If you specify a time-out value, Join returns true if the thread terminated, and false if Join timed out.
The following example executes a second thread and then calls Join to wait for the second thread to terminate. Because the second thread takes around five seconds to execute, but the Join method specifies a time-out of three seconds, Join will always time out and the example will display a message to the console.
using System;
using System.Threading;

public class ThreadFinishExample {

    private static void DisplayMessage() {

        // Display a message to the console 5 times.
        for (int count = 0; count < 5; count++) {

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

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

    public static void Main() {

        // Create a ThreadStart delegate instance that references
        // DisplayMessage.
        ThreadStart method = new ThreadStart(DisplayMessage);

        // Create a new Thread object and pass the ThreadStart
        // delegate instance to its constructor.
        Thread thread = new Thread(method);

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

        // Start the second thread.
        thread.Start();

        // Block until the second thread finishes, or time out after
        // 3 seconds.
        if (!thread.Join(3000)) {

            Console.WriteLine("{0} : Join timed out !!",  
                DateTime.Now.ToString("HH:mm:ss.ffff"));
        }

        // Wait to continue.
        Console.WriteLine("Main method complete. Press Enter.");
        Console.ReadLine();
    }
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail