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
Post a Comment