Task finishes before expected

62 Views Asked by At

I have this method: 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. But unfortunately it doesn`t. If I comment the line s_Finishing = true; The task runs forever - and allows to MyMethod to be completed How can I solve the issue?

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()                        });
}
1

There are 1 best solutions below

0
On BEST ANSWER

I believe your problem is here:

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

You can't use async with ForEach. It's extremely rare to need to do both parallel (CPU-bound) and async (I/O-bound) together in the same method. If you just want concurrency (which I suspect), use Task.WhenAll instead of ForEach. If you really do need both CPU parallelism and async, then use TPL Dataflow.