Thread.Join在C#中的意义是什么?
C#中Thread.Join方法的意义是什么Thread.Join在C#中的意义是什么?,c#,multithreading,C#,Multithreading,C#中Thread.Join方法的意义是什么 MSDN说它会阻止调用线程,直到线程终止。有人能用一个简单的例子来解释这一点吗?假设您有一个主线程,它将一些工作委托给工作线程。主线程需要工作线程正在计算的一些结果,因此在所有工作线程完成之前,它无法继续 在这种情况下,主线程将在每个工作线程上调用Join()。在所有Join()调用返回后,主线程知道所有工作线程都已完成,并且计算结果可供其使用。想象您的程序在Thread1中运行。然后,您需要开始一些计算或处理-启动另一个线程-Thread2。然后,
MSDN说它会阻止调用线程,直到线程终止。有人能用一个简单的例子来解释这一点吗?假设您有一个主线程,它将一些工作委托给工作线程。主线程需要工作线程正在计算的一些结果,因此在所有工作线程完成之前,它无法继续
在这种情况下,主线程将在每个工作线程上调用
Join()
。在所有Join()
调用返回后,主线程知道所有工作线程都已完成,并且计算结果可供其使用。想象您的程序在Thread1
中运行。然后,您需要开始一些计算或处理-启动另一个线程-Thread2
。然后,如果希望线程1等待Thread2
结束,则执行Thread1.Join()代码>和Thread1
将不会继续执行,直到Thread2
完成
以下是。简单示例方法中的说明:
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()
基本上是while(thread.running){}
int fibsum=1;
线程t=新线程(o=>
{
对于(int i=1;i<20;i++)
{
fibsum+=fibsum;
}
});
t、 Start();
t、 Join();//如果对此行进行注释,将执行WriteLine
//在线程完成之前,结果将是错误的
控制台写入线(fibsum);
这只是对现有答案的补充,解释了Join
的作用
调用Join
也有允许消息泵处理消息的副作用。有关这可能相关的情况,请参见此 它很简单,但也很无用:一个线程。紧接着启动一个线程。Join违背了使用第二个线程的全部目的。(我知道这是一个玩具示例,但仍然…@Heinzi,它只是按照要求演示了Join
方法的基本行为。它从来没有打算描述一个真实的场景。MSDN说,“在继续执行标准COM和SendMessage传输的同时,阻止调用线程,直到线程终止。”。执行标准COM的含义是什么?sendMessage pumping的含义是什么?事实上,这是不正确的。如果希望Thread1
等待Thread2
结束,则执行Thread2.Join()
,而不是Thread1.Join()
。
{
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);