我有一个 List
的 Task<bool>
我想迭代它并根据等待的结果决定是继续还是中断但具有讽刺意味的是 foreach
只是执行任务,await 关键字不起作用
这是我的代码
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;
}
结果:两个函数都执行了。
问题:我如何在 foreach
中使用 await ?
提前谢谢。
最佳答案
您可以使用 await
在 foreach 中,就像您现在所做的那样。
Result : Both functions are execute.
这两个函数应该执行。 result
直到 Method2
才设置为 false返回,此时两者都已经运行。您还同时启动了 Task<bool>
你之前的实例 await
两者都(可能)在您的 foreach 循环之前运行。
颠倒你的方法的顺序,它们将不会同时运行必然(尽管它们可能,因为你正在启动它们):
var tList = new List<Task<bool>> { Method2(), Method1()};
如果你想完全延迟这个,你可以写成:
var tList = new List<Func<Task<bool>>> { Method2, Method1};
foreach (var taskFunc in tList)
{
var result = await taskFunc();
if(!result)
break;
}
关于c# - 在 Foreach 关键字中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16349519/