Block until a thread finishes, or timeout after 2 seconds : Thread Join « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MainClass
{
    private static void DoCount()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("{0} : DoCount thread",DateTime.Now.ToString("HH:mm:ss.ffff"));

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

    public static void Main()
    {
        Thread thread = new Thread(DoCount);

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

        thread.Start();

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

        // Block again until the DoCount thread finishes with no timeout.
        thread.Join();
    }
}
14:49:28.6093 : Starting DoCount thread.
14:49:28.6250 : DoCount thread
14:49:29.6250 : DoCount thread
14:49:30.6250 : Join timed out !!
14:49:30.6250 : DoCount thread
14:49:31.6250 : DoCount thread
14:49:32.6250 : DoCount thread








20.5.Thread Join
20.5.1.Use Join() to wait for threads to end
20.5.2.Threads Joining
20.5.3.Thread joins
20.5.4.Block until a thread finishes, or timeout after 2 seconds