任务提前完成

Task finishes before expected

我有这个方法: 私有静态异步任务 MyMethod(); 它是这样调用的:

public static void Main()
{
s_Finishing = false;
Task printTask = PrintStatistics();
MyMethod(serversSawa, serversSterling).Wait();
s_Finishing = true;
}

我预计 PrintStatistics 将仅在 MyMethod 完成后停止到 运行。但不幸的是它没有。如果我注释行 s_Finishing = true; The task 运行s forever - 并允许 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()                        });
}

我相信你的问题出在这里:

Parallel.ForEach(..., async ...);

您不能将 asyncForEach 一起使用。 需要以相同的方法同时执行并行(CPU-绑定)和async(I/O-bound)的情况极为罕见。如果您只想并发(我怀疑),请使用 Task.WhenAll 而不是 ForEach。如果您确实需要 CPU 并行度和 async,请使用 TPL 数据流。