Reputation: 5259
I have a List
of Task<bool>
that i want to iterate it and depending on the awaited result i decide whether to continue or break but ironically the foreach
just executes the tasks and await keyword does not work
Here is my 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 are execute.
Question : How could i use await inside foreach
?.
And thanks in advance.
Upvotes: 6
Views: 6357
Reputation: 564433
You can use await
within a foreach exactly as you are doing now.
Result : Both functions are execute.
Both functions should execute. The result
isn't set to false until Method2
returns, at which point both have already run. You're also starting both Task<bool>
instances before you await
either, so both are (potentially) running before your foreach loop.
Reverse the order of your methods, and they won't both necessarily run (though they may, as you're starting them):
var tList = new List<Task<bool>> { Method2(), Method1()};
If you want to delay this completely, you could write it as:
var tList = new List<Func<Task<bool>>> { Method2, Method1};
foreach (var taskFunc in tList)
{
var result = await taskFunc();
if(!result)
break;
}
Upvotes: 10