开发者

C# Joining Threads

开发者 https://www.devze.com 2022-12-08 02:10 出处:网络
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

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 th开发者_如何学运维at 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.


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.


  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.

0

精彩评论

暂无评论...
验证码 换一张
取 消