c# - Task finishes before expected -
i have method: private static async task mymethod(); , invocated way:
public static void main() { s_finishing = false; task printtask = printstatistics(); mymethod(serverssawa, serverssterling).wait(); s_finishing = true; }
i expect printstatistics stop run after mymethod completed. unfortunately doesn`t. if comment line s_finishing = true;
task runs forever - , allows mymethod completed how can solve 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() }); }
i believe problem here:
parallel.foreach(..., async ...);
you can't use async
foreach
. it's extremely rare need both parallel (cpu-bound) , async
(i/o-bound) in same method. if want concurrency (which suspect), use task.whenall
instead of foreach
. if need both cpu parallelism , async
, use tpl dataflow.
Comments
Post a Comment