c# - TPL - task is not awaited -


been using tpl quite while, , still have mysteries solve :)

when run in console, expect work done before logs "jobs done":

await startattachedasync(() => {   var result = parallel.for(0, 4, async =>   {     callcontext.logicalsetdata("contextid", i);     await task.run(async () =>     {        await task.delay(2000);        await task.run(async () =>        {           await task.delay(2000);           write("step c done " + i);        });        write("step b done " + i);      });      write("step done " + i);    });    console.writeline("for done: completed = " + result.iscompleted); }); console.writeline("jobs done");   private static async task startattachedasync(action action) {    await task.factory.startnew(action,    cancellationtoken.none,     taskcreationoptions.attachedtoparent,     taskscheduler.default); } 

gives me:

for loop done: completed = true jobs done step c done 0 step c done 2 step c done 3 step c done 1 step b done 1 step done 1 step b done 0 step done 0 step b done 3 step done 3 step b done 2 step done 2 

why loop done without awaiting subtasks?

because parallel.for async method body not awaited. happens start fire , forget tasks in loop construct.

better hold reference tasks create , await task.whenall(tasks);

what's reason use parallel.for . can't create bunch of tasks without it?

in current code do:

await startattachedasync(() => {     var tasks = new list<task>();      var result = parallel.for(0, 4, async =>     {         callcontext.logicalsetdata("contextid", i);         tasks.add(task.run(async () =>         {             await task.delay(2000);             await task.run(async () =>             {                 await task.delay(2000);                 write("step c done " + i);             });             write("step b done " + i);          }));          write("step done " + i);     });      await task.whenall(tasks);      console.writeline("for done: completed = " + result.iscompleted); });     

Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -