What is the significance of Thread.Join in C#?
What is the signific开发者_运维问答ance of the Thread.Join method in C#?
MSDN says that it blocks the calling thread until a thread terminates. Can anybody explain this with a simple example?
Join()
is basically while(thread.running){}
{
thread.start()
stuff you want to do while the other thread is busy doing its own thing concurrently
thread.join()
you won't get here until thread has terminated.
}
int fibsum = 1;
Thread t = new Thread(o =>
{
for (int i = 1; i < 20; i++)
{
fibsum += fibsum;
}
});
t.Start();
t.Join(); // if you comment this line, the WriteLine will execute
// before the thread finishes and the result will be wrong
Console.WriteLine(fibsum);
Suppose you have a main thread that delegates some work to worker threads. The main thread needs some results that the workers are computing, so it cannot continue until all worker threads have finished.
In this scenario, the main thread would call Join()
on each of the worker threads. After all the Join()
calls have returned, the main thread knows that all worker threads have finished, and that the computed results are available for its consumption.
Imagine your program runs in Thread1
. Then you need to start some calculation or processing - you start another thread - Thread2
. Then if you want your Thread1 wait until Thread2
ends you execute Thread1.Join();
and Thread1
will not continue its execution until Thread2
finishes.
Here is description in MSDN.
The simple example approach:
public static void Main(string[] args)
{
Console.WriteLine("Main thread started.");
var t = new Thread(() => Thread.Sleep(2000));
t.Start();
t.Join();
Console.WriteLine("Thread t finished.");
}
The program starts by printing a message to the screen and then starting a new thread that just pauses for 2 seconds before terminating. The last message is only printed after the t
thread finishes executing because the Join
method call blocks the current thread until the t
thread terminates.
static void Main()
{
Thread t = new Thread(new ThreadStart(some delegate here));
t.Start();
Console.WriteLine("foo");
t.Join()
Console.WriteLine("foo2");
}
In your delegate you would have another call like this:
Console.WriteLine("foo3");
Output is:
foo
foo3
foo2
This is just to add to the existing answers, that explain what Join
does.
Calling Join
also has the side effect of allowing the message pump to handle messages. See this knowledge base article for situations where this may be relevant.
精彩评论