【发布时间】:2016-03-20 13:45:59
【问题描述】:
我希望在打印结果之前完成 for 循环,在:
for (int i = 0; i < 5; i++)
{
(new System.Threading.Thread(() =>
{
if (TimeTakingMethod())
{
++nResult;
}
})).Start();
}
Console.WriteLine("Count = " + nResult);
但 Console.WriteLine 不会等待这些线程完成,因为打印是在主线程上完成的。
如果我将其更改为:
System.Threading.Thread t = new System.Threading.Thread(() =>
{
for (int i = 0; i < 5; i++)
{
(new System.Threading.Thread(() =>
{
if (TimeTakingMethod())
{
++nResult;
}
})).Start();
}
});
t.Start();
t.Join();
Console.WriteLine("Count = " + nResult);
仍然无法解决问题,因为不会等待嵌套线程。
有什么简单的解决方案吗?感谢您完成此操作。
【问题讨论】:
-
这样使用线程有什么意义?你只是等到它完成......
-
模糊逻辑?我建议你解释一下你在做什么,为什么?没有明显原因的嵌套线程
-
Idos 和 Saleem,等待是因为只有在循环处理之后才应该打印结果。我在那里使用了线程,因为循环的每次迭代都需要时间。我在问题栏中给出的解释是复杂任务的简化版本,因此这个问题可能会使程序看起来不需要多线程。 Crashmstr,我同意,谢谢。该页面上的以下内容以及该页面上给出的其他答案都有帮助: List
threads=new List (); //将你的线程添加到这个集合中 threads.WaitAll(); -
TVOHM 和 YottaGinneh,感谢您的回答,这很有帮助。
标签: c# multithreading for-loop nested