Thread.Join()
block next line to execute and wait for a specific thread to complete.
And that's precisely why people use Thread.Join()
.
Yes, you want your different threads doing their different things separately as much as possible, but when Thread A needs something that Thread B is obtaining, or can't do something until Thread B has done something, then the easiest way to get to that point is to use Thread.Join()
.
That's not terribly useful in the example in your question, because there you have three threads one of which is doing nothing useful.
A slightly more realistic version would be:
Thread thd1 = new System.Threading.Thread(new ThreadStart(DoWork));
thd1.Start();
DoWork();
thd1.Join();
Here you've two threads doing two threads-worth of work. By the time we get to thd1.Join()
it's likely that thd1
has already completed and joining is a nop, but just in case we wait to make sure it's finished.
Another more realistic example is when you create several threads and then join those several threads because while it's wasteful to have the creating thread just waiting, it's simpler to code a loop that sets up X threads than a loop that sets up X-1 threads and does the work of that final item.
Avoiding Join
ing as long as possible (or at all) is certainly a good idea that will often give you greater efficient use of available threads, but Join
ing is simple, and simple is good too.