![](/img/trans.png)
[英]Why does my C# code stall when calling back into C++ COM until Task.Wait/Thread.Join?
[英]Thread.Join versus Task.Wait
考慮以下代碼。
static void Main(string[] args)
{
Thread t = new Thread(Foo);
t.Start();
Console.WriteLine("Main ends.");
//t.Join();
}
static void Foo()
{
for (int x = 0; x < 1000000000; x++) ;
Console.WriteLine("Foo ends.");
}
static void Main(string[] args)
{
Task t = new Task (Foo);
t.Start();
Console.WriteLine("Main ends.");
t.Wait();
}
static void Foo()
{
for (int x = 0; x < 1000000000; x++) ;
Console.WriteLine("Foo ends.");
}
使用Task
,我們需要t.Wait()
在主線程結束之前等待線程池線程完成,但使用Thread
,我們不需要t.Join
來獲得相同的效果。
為什么t.Join()
來防止主線程在其他生成的線程結束之前結束?
有幾個區別,但是回答您的問題的重要部分是線程池使用后台線程,並且這些線程不會阻止現有的進程。 您可以在這里閱讀更多內容。
t.wait() 不能在任務已經啟動后使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.