The thread. Join () method, as its name implies, adds something to a thread.
On msdn, the function is to block the "Call thread" until a thread ends.
The translation explanation is a bit obscure. For example:
Static void main ()
{
Thread t = new thread (New threadstart (threadmethod ));
T. Start ();
T. Join ();
Console. writeline ("I am main thread ");
Console. Read ();
}
Void threadmethod ()
{
...
}
From aboveCode, We can see there are two threads: main thread and thread t
Return to join. The caller here is the main thread. The main thread calls the join method of thread t, which causes the main thread to be blocked until the execution of thread t is complete and is returned to the main thread.
Simply understand, call T in the main thread. join (), that is, the code of the T thread added to the main thread. After the T thread is executed, the main thread (caller) can run normally.
Sample Code:
Code
Static Void Main ( String [] ARGs)
{
// Autoresetevent autoevent = new autoresetevent (false );
Thread regularread = New Thread ( New Threadstart (threadmethod ));
Regularread. Start ();
Threadpool. queueuserworkitem ( New Waitcallback (workmethod1), regularread );
Console. writeline ( " I am main thread! " );
// Regularread. Join ();
Console. writeline ( " I am main thread! " );
// Autoevent. waitone ();
Console. Read ();
}
Static Void Threadmethod ()
{
For ( Int I = 0 ; I < 5 ; I ++ )
{
Console. writeline ( " Threadone executes for {0} Times, executing threadmethod, is {1} from the thread pool. " , I + 1 , Thread. currentthread. isthreadpoolthread ? "" : " Not " );
Thread. Sleep ( 1000 );
}
}
Static Void Workmethod1 ( Object Stateinfo)
{
Console. writeline ( " Threadtwo, executing workmethod, is {0} form the thread pool. " , Thread. currentthread. isthreadpoolthread ? "" : " Not " );
// (Autoresetevent) stateinfo). Set ();
(Thread) stateinfo). Join ();
For ( Int I = 0 ; I < 5 ; I ++ )
{
Console. writeline ( " Threadtwo execution at {0}, executing workmethod, is {1} form the thread pool. " , I + 1 , Thread. currentthread. isthreadpoolthread ? "" : " Not " );
}
}
There are three threads in the Code: the main thread, regularread, and one thread in the thread pool. The regularread. Join () method is called in the thread pool;
Execution result:
We can see that the content in the thread loop in the thread pool is executed only after the regularread content is executed.