等待.NET 4.0:有意义的堆栈跟踪

时间:2013-07-29 10:27:49

标签: c# asynchronous exception-handling task-parallel-library async-await

我有一个使用.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

使用await时,如何从.NET 4.0项目中获取有用的堆栈跟踪?

更新

“旧”AsyncTargetingPack确实会产生更好的堆栈跟踪。这个问题似乎已在“新”Microsoft.Bcl.Async中引入。

1 个答案:

答案 0 :(得分:7)

Foo更改为此似乎可以获得更好的结果:

private static async Task Foo()
{
    await DoSomething().ContinueWith(t => Log(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}

更新:但是,缺点是每次使用.ContinueWith关键字时都必须使用相同的await。即,如果等待等待的东西,你也需要.ContinueWith