Saturday, February 23, 2013

Threading: 07- Waiting for a thread to complete, but just for a while, Thread.Join

We can wait for a thread to complete, but we cannot wait indefinitely sometimes. .Net allows us to wait for a thread to complete just for a while, using Thread.Join method.

Thread.Join method, receives a timeout in milliseconds and waits up to that period. If it is still running, it stops waiting and returns false, else returns true.


using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Main Started");
        var th = new Thread(Greet); // Create new thread
        th.Start(new object[] { "Bob", "Good Morning" });  // Execute Greet method in the created thread
        if (th.Join(800))
            Console.WriteLine("Greeting finished");
            Console.WriteLine("Greeting is still running");
        Console.WriteLine("Main Completed");

    private static void Greet(object info) {
        Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);



Main Started
Greeting is still running
Main Completed
Hi Bob, Good Morning!

No comments:

Post a Comment