Thread.Join方法在c#中有什么意义?
Thread.Join方法在c#中有什么意义?
MSDN表示它会阻塞调用线程,直到线程终止。 有人可以用一个简单的例子来解释这个吗?
Join()
基本上是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);
假设您有一个主线程将一些工作委托给工作线程。 主线程需要一些工作者正在计算的结果,因此在所有工作线程完成之前它不能继续。
在这种情况下,主线程将在每个工作线程上调用Join()
。 在返回所有Join()
调用之后,主线程知道所有工作线程都已完成,并且计算结果可供其使用。
想象一下你的程序在Thread1
运行。 然后你需要开始一些计算或处理 – 你启动另一个线程 – Thread2
。 然后,如果你想让你的Thread2
等到Thread2
结束你执行Thread1.Join();
在Thread2
完成之前, Thread2
将不会继续执行。
这是MSDN中的描述。
简单的示例方法:
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."); }
程序首先将消息打印到屏幕,然后启动一个新的线程,在终止之前暂停2秒钟。 最后一条消息仅在t
线程执行完毕后打印,因为Join
方法调用会阻塞当前线程,直到t
线程终止。
static void Main() { Thread t = new Thread(new ThreadStart(some delegate here)); t.Start(); Console.WriteLine("foo"); t.Join() Console.WriteLine("foo2"); }
在你的委托中你会有另外一个这样的电话:
Console.WriteLine("foo3");
输出是:
foo foo3 foo2
这只是为了补充现有的答案,解释了Join
作用。
调用Join
还具有允许消息泵处理消息的副作用。 有关可能相关的情况,请参阅此知识库文章 。