我有一个使用 .NET 4.0 的 C# 控制台应用程序项目,并安装了 Microsoft.Bcl.Async 包。我使用这段代码:
internal class Program
{
private static void Main(string[] args)
{
Foo().Wait();
}
static void Log(Exception ex)
{
}
private static async Task Foo()
{
try
{
await DoSomething();
}
catch (Exception ex)
{
Log(ex);
}
}
private static async Task DoSomething()
{
throw new DivideByZeroException();
}
}
如果我在 Log 方法中放置一个断点,我会得到 DivideByZero 异常,但我看到的堆栈跟踪是:
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.GetResult()
at AsyncStacks.Program.<Foo>d__0.MoveNext() in p:\Sandbox\AsyncStacks\AsyncStacks\Program.cs:line 25
这个堆栈跟踪几乎没有用,因为它没有告诉我异常实际上是在哪里引发的。
如果我将项目更改为面向 .NET 4.5,我会得到一个更有用的异常:
at AsyncStacks.Program.<DoSomething>d__3.MoveNext() in p:\Sandbox\AsyncStacks\AsyncStacks\Program.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at AsyncStacks.Program.<Foo>d__0.MoveNext() in p:\Sandbox\AsyncStacks\AsyncStacks\Program.cs:line 25
使用 .NET 4.0 项目时如何获得有用的堆栈跟踪await
?
更新
“旧” AsyncTargetingPack确实会抛出更好的堆栈跟踪。该问题似乎已在“新” Microsoft.Bcl.Async中引入。