Joining a Thread

You can block until another thread ends by calling Join:

class JoinDemo {
  static void Main() {
    Thread t = new Thread (delegate() { Console.ReadLine(); });
    t.Start();
    t.Join();    // Wait until thread t finishes
    Console.WriteLine ("Thread t's ReadLine complete!");
  }
}

The Join method also accepts a timeout argument – in milliseconds, or as a TimeSpan, returning false if the Join timed out rather than found the end of the thread. Join with a timeout functions rather like Sleep – in fact the following two lines of code are almost identical:

Thread.Sleep (1000);
Thread.CurrentThread.Join (1000);

(Their difference is apparent only in single-threaded apartment applications with COM interoperability, and stems from the subtleties in Windows message pumping semantics described previously: Join keeps message pumping alive while blocked; Sleep suspends message pumping).

 

 

using System;
using System.Threading;
using System.Runtime.Remoting.Contexts;
//csc thread_contb_join.cs
namespace ex_sync
{
public class Con_TB : ContextBoundObject {

public void proc_thread()
{
Thread.Sleep (1000);
voter_in();

}

public void process()
{
Thread t1 = new Thread(voter_in);
t1.Name ="voter_in";
Console.WriteLine("\t--Start-voter-in--");
t1.Start();
Console.WriteLine("Thread No : {0}",Thread.CurrentThread.GetHashCode().ToString());
//Thread.Sleep(1000);
Console.WriteLine("\t--Join-voter-in--");
t1.Join();

}
public void voter_in() {
Console.WriteLine("--Enter-voter-in--");
Console.WriteLine("Thread No : {0}",Thread.CurrentThread.GetHashCode().ToString());
voter_out();

}
public void voter_out() {
Console.WriteLine("--Start-voter-out--");
Console.WriteLine("Thread No : {0}",Thread.CurrentThread.GetHashCode().ToString());
Console.WriteLine(DateTime.Now);
Console.WriteLine("--Exit-voter-out--");

}
}

public class Test {
public static void Main() {
Con_TB at = new Con_TB();
Thread []t = new Thread[3];
Console.WriteLine("Thread No : {0}",Thread.CurrentThread.GetHashCode().ToString());
Console.WriteLine("Main,Thread, " + "is {0}from thread pool.",
Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");
ThreadStart ts = new ThreadStart(at.proc_thread);
int i ;
for(i = 0; i < 3; i++){ t[i] = new Thread(ts); }
for(i = 0; i < 3; i++){ t[i].Start(); }
for(i = 0; i < 3; i++){ t[i].Join(); }
Console.WriteLine("---Void Main-- {0}",Thread.CurrentThread.GetHashCode().ToString());
Console.ReadLine();
}
}
}