【发布时间】:2018-12-05 13:35:29
【问题描述】:
我有非常简单的代码,我无法理解它的行为。
class Program
{
static void Main(string[] args)
{
// Get reference to main thread
Thread mainThread = Thread.CurrentThread;
// Start second thread
new Thread(() =>
{
Console.WriteLine("Working...");
Thread.Sleep(1000);
Console.WriteLine("Work finished. Waiting for main thread to end...");
mainThread.Join(); // Obviously this join cannot pass
Console.WriteLine("This message never prints. Why???");
}).Start();
Thread.Sleep(300);
Console.WriteLine("Main thread ended");
}
}
这个永无止境的程序的输出是:
在职的... 主线程结束 工作完成。等待主线程结束...为什么线程的代码卡在Join() 方法调用上?通过其他打印输出可以发现,在Join()调用之前,mainThread的属性IsAlive设置为false,ThreadState为Background, Stopped, WaitSleepJoin。消除睡眠也没有任何区别。
这种行为的原因是什么? Join() 方法和Main 方法的执行到底有什么奥秘?
【问题讨论】:
-
主线程终止通常与进程终止同时发生。我猜这是对你的代码做你不想要的事情
标签: c# .net multithreading join main