问题描述
我有这个代码,它是为了证明问题而剥离的更大功能的骨架:
I have this code, it is the skeleton of larger functionality stripped down to prove the problem:
var tasks = Enumerable.Range(0, 10)
.Select(laneNo => Task.Run(() => Console.WriteLine($"Starting generator for lane {laneNo}")));
for(int r=0; ;++r)
{
Task.Delay(TimeSpan.FromSeconds(3)).Wait();
Console.WriteLine($"Iteration {r} at {DateTime.Now}");
}
我从来没有看到启动生成器"打印到控制台,但我确实看到迭代每 3 秒触发一次 - 有些事情导致这些任务没有进展(在实际代码中,它们运行了很长一段时间,但删除它不会影响问题).
I never see "Starting generator" printed to Console but I do see the iteration fire every 3 seconds - something is causing those tasks not to progress (in the real code they run for a significant period but removing that doesn't affect the problem).
为什么第一批任务没有运行?我的理论是它与 Task.Delay
相关?
Why are the first bunch of Tasks not running? My theory is it's related to Task.Delay
?
推荐答案
LINQ Select
已延迟执行;它只是定义了一个迭代器,所以你的 Task
不会被生成.
LINQ Select
has deferred execution; it simply defines an iterator, so your Task
s are not being generated.
您可以使用 Task.WhenAll(IEnumerable)
,它将迭代并等待每个Task
,生成新的Task代码>在所有提供的任务也完成后完成:
You could make use of Task.WhenAll(IEnumerable<Task>)
, which will iterate and await each Task
, generating new Task
that completes once all the provided tasks have also completed:
var tasks = Enumerable.Range(0, 10)
.Select(laneNo => Task.Run(() => Console.WriteLine($"Starting generator for lane {laneNo}")));
await Task.WhenAll(tasks);
这篇关于为什么并行任务没有运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!