c# - Await Inside Foreach Keyword -


i have list of task<bool> want iterate , depending on awaited result decide whether continue or break ironically foreach executes tasks , await keyword not work

here code

private async void execute(object sender, eventargs e) {     var tlist = new list<task<bool>> { method1(), method2()};      foreach (var task in tlist)     {         var result = await task;          if(!result)             break;     } }  public async task<bool> method1() {     await task.delay(1000);     console.writeline("method1");     return false; }  public async task<bool> method2() {     await task.delay(1000);     console.writeline("method2");     return true; } 

result : both functions execute.

question : how use await inside foreach ?.

and thanks in advance.

you can use await within foreach doing now.

result : both functions execute.

both functions should execute. result isn't set false until method2 returns, @ point both have run. you're starting both task<bool> instances before await either, both (potentially) running before foreach loop.

reverse order of methods, , won't both necessarily run (though may, you're starting them):

var tlist = new list<task<bool>> { method2(), method1()}; 

if want delay completely, write as:

var tlist = new list<func<task<bool>>> { method2, method1};  foreach (var taskfunc in tlist) {     var result = await taskfunc();      if(!result)         break; } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -