Friday, June 6, 2008

Just Waiting On Thread

The Join method of a thread is what you use to wait for a thread to finish

===Code Starts===
using System;
using System.Threading;
namespace ConsoleApplicationThread
{
public class MultiThreadStart
{
public static void ThreadMethod()
{
for (int i = 0; i < class="blsp-spelling-error" id="SPELLING_ERROR_4">WriteLine("ThreadMethod {1}: {0}", i,Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
}
}
public static void Main()
{
Console.WriteLine("Main thread: Create multiple threads");
Thread thread1 = new Thread(new ThreadStart(ThreadMethod));
Thread thread2 = new Thread(new ThreadStart(ThreadMethod));
Thread thread3 = new Thread(new ThreadStart(ThreadMethod));
Thread thread4 = new Thread(new ThreadStart(ThreadMethod));

Console.WriteLine("Main thread: Start threads");
thread1.Start();
thread2.Start();
thread3.Start();
thread4.Start();
Console.WriteLine("Main: Call Join() on each thread to wait for thread to end.");
thread1.Join();
thread2.Join();
thread3.Join();
thread4.Join();
Console.WriteLine("Main: All threads have ended");
Console.ReadLine();
}
}
}

No comments: