[英]Task finishes before expected
I have this method: private static async Task MyMethod();我有这个方法:private static async Task MyMethod(); And it is invocated this way:
它是这样调用的:
public static void Main()
{
s_Finishing = false;
Task printTask = PrintStatistics();
MyMethod(serversSawa, serversSterling).Wait();
s_Finishing = true;
}
I expect that PrintStatistics will stop to run only after MyMethod is completed.我希望 PrintStatistics 只有在 MyMethod 完成后才会停止运行。 But unfortunately it doesn`t.
但不幸的是它没有。 If I comment the line
s_Finishing = true;
如果我评论这行
s_Finishing = true;
The task runs forever - and allows to MyMethod to be completed How can I solve the issue?任务永远运行 - 并允许完成 MyMethod 如何解决问题?
private static async Task PrintStatistics()
{
while (!s_Finishing)
{
long total = 0;
await Task.Delay(TimeSpan.FromSeconds(20));
foreach (var statistic in s_Statistics)
{
ToolsTracer.Trace("{0}:{1}", statistic.Key, statistic.Value);
total += statistic.Value;
}
foreach (var statistic in s_StatisticsRegion)
{
ToolsTracer.Trace("{0}:{1}", statistic.Key, statistic.Value);
}
ToolsTracer.Trace("TOTAL:{0}", total);
ToolsTracer.Trace("TIME:{0}", s_StopWatch.Elapsed);
}
}
private static async Task MyMethod()
{
Parallel.ForEach(
data,
new ParallelOptions { MaxDegreeOfParallelism = 20 }, async serverAndCluster =>
{
await someMethod() });
}
I believe your problem is here:我相信你的问题在这里:
Parallel.ForEach(..., async ...);
You can't use async
with ForEach
.您不能将
async
与ForEach
一起使用。 It's extremely rare to need to do both parallel (CPU-bound) and async
(I/O-bound) together in the same method.需要在同一方法中同时执行并行(受 CPU 限制)和
async
(受 I/O 限制)的情况极为罕见。 If you just want concurrency (which I suspect), use Task.WhenAll
instead of ForEach
.如果您只想要并发(我怀疑),请使用
Task.WhenAll
而不是ForEach
。 If you really do need both CPU parallelism and async
, then use TPL Dataflow.如果您确实需要 CPU 并行性和
async
,请使用 TPL 数据流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.