Getting a meaningful stack trace when using async code

So – is there any way to get a more meaningful stack trace when running async tasks?

Yes, you can use ExceptionDispatchInfo.Capture that was introduced in .NET 4.5 for async-await speficially:

private static void ThrowError(Task t)
{
    if (t.IsFaulted)
    {
        Exception exception = 
            t.Exception.InnerExceptions != null && t.Exception.InnerExceptions.Count == 1 
                ? t.Exception.InnerExceptions[0] 
                : t.Exception;

        ExceptionDispatchInfo.Capture(exception).Throw();
    }
}

“You can use the ExceptionDispatchInfo object that is returned by this method at another time and possibly on another thread to rethrow the specified exception, as if the exception had flowed from this point where it was captured to the point where it is rethrown.
If the exception is active when it is captured, the current stack trace information and Watson information that is contained in the exception is stored. If it is inactive, that is, if it has not been thrown, it will not have any stack trace information or Watson information.”

However, keep in mind that exceptions from async code are generally less meaningful than you would like as all exceptions are thrown from inside the MoveNext method on the state machine generated by the compiler.

Leave a Comment