What is the significance 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 a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.
Joining a thread means waiting for it to terminate, which can be seen as a specific usage of condition variables. Using the pthread_join subroutine alows a thread to wait for another thread to terminate.
It is perfectly fine. No join or System. exit necessary. Each thread lives its own life.
Threads operate faster than processes due to following reasons: 1) Thread creation is much faster. 2) Context switching between threads is much faster. 4) Communication between threads is faster.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With