using System;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
var p = new Program();
p.Loop();
}
public async void Loop()
{
for (int i = 0; i < 5; ++i)
{
try
{
Console.WriteLine(i);
var result = await SomeTask();
Console.WriteLine(result);
}
catch (Exception)
{
Console.WriteLine("Error" + i);
}
}
}
public async Task<string> SomeTask()
{
await Task.Delay(1);
throw new Exception();
return "Result";
}
}
输出量
0
Error0
1
我希望输出更像这样:
0
Error0
1
Error2
2
Error2
3
Error4
4
为什么在0后停止?
最佳答案
您不是在等待async
操作完成,因此应用程序在操作完成之前就已结束。
您不应在事件处理程序之外使用async void
。 async void
不会返回等待状态,因此调用方法只是继续前进(并退出应用程序)。您应该返回一个Task
并对其进行await
(或在Main
的情况下使用Task.Wait
):
public static void Main()
{
var p = new Program();
p.LoopAsync().Wait();
}
public async Task LoopAsync()
{
for (int i = 0; i < 5; ++i)
{
try
{
Console.WriteLine(i);
var result = await SomeTask();
Console.WriteLine(result);
}
catch (Exception)
{
Console.WriteLine("Error" + i);
}
}
}
输出:
0
Error0
1
Error1
2
Error2
3
Error3
4
Error4
关于c# - 在循环中捕获异步错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29291863/