views:

113

answers:

2
+2  Q: 

C# Joining Threads

I'm trying to obtain a good understanding of multi-threading in C# and I'm a bit confused about the applicability of the Thread.Join method. Microsoft says that it "Blocks the calling thread until a thread terminates." Two questions:

  1. Given the following example, which thread is actually blocked while the other is working toward termination?

  2. Doesn't the fact that one thread is blocked while the other is executing toward termination actually defeat the purpose of multi-threads? (So I assume you only want to join in certain situations. What might those be?)

static int Main()
    {
      Alpha oAlpha = new Alpha();
      Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
      oThread.Start();
      oThread.Join();
    }

I should also note that it is wholly possible that I'm not doing something correct here.

+2  A: 

Main is blocked until oThread Completes.

The idea is that you can terminate on thread cleanly and wait for it to clean up after itself, rather than killing the thread sloppily.

It is also useful for starting a batch of three or four independent processes, and then continuing once ALL of them complete.

John Gietzen
So in this simplistic example, removing the join could result in the current thread (that running main) from falling through the end of the method before the oThread finishes, thus killing the oThread and leaving it in a bad state. If this is right, then I assume that if the original thread terminates, then the oThread terminates as well. Correct?
L. Moser
It depends. If the thread is set as a `Background` thread, then yes, that is exactly how it would work. If you have that property set to false, it will keep the process open until it terminates.
John Gietzen
A: 
  1. the thread that is running the Main() method blocks.

  2. Threads often need to synchronize, for instance, if you didn't want your main method to exit until all the work was done. In your example, there's no benefit, but you could insert useful work in between the Start() and Join() calls. This is particularly useful if you spin off multiple threads and then join them all.

Jeremy Huiskamp