Skip to content

new StackTrace() inside async methods -> Useless, Lack of frames with sync caller method (initiator) #60764

Open

Description

@feeleen

Exception's stack trace from async code was significantly improved to be more clear and keep the chain of callers from sync code part.
But if we try to get new StackTrace() at runtime, then we are get back at the very bottom of the ladder. This StackTrace is useless

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Foo().GetAwaiter().GetResult();
    }

    static async Task Foo()
    {
        await Task.Delay(100);
        A a = new();
    }
}

public class A
{
    public A()
    {
        Console.WriteLine("In this stackTrace we know nothing about 'Main':");
        new StackTrace().GetFrames().ToList()
            .ForEach(x => Console.WriteLine(x.GetMethod()?.Name));
		
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Here, in exception stacktrace we will see 'Main':");
        throw new Exception();
    }
}

https://dotnetfiddle.net/u9gcR6

output:

In this stackTrace we know nothing about 'Main':
.ctor
MoveNext
ExecutionContextCallback
RunInternal
MoveNext
MoveNext
RunOrScheduleAction
RunContinuations
FinishContinuations
TrySetResult
CompleteTimedOut
<.ctor>b__1_0
CallCallback
Fire
FireNextTimers
AppDomainTimerCallback


Here, in exception stacktrace we will see 'Main':
Unhandled exception. System.Exception: Exception of type 'System.Exception' was thrown.
   at A..ctor()
   at Program.Foo()
   at Program.Main()
Command terminated by signal 6

Is there a chance that this will be fixed/improved somehow?

Activity

  1. ghost added
    untriaged
    on Oct 22, 2021
  2. feeleen commented on Oct 22, 2021

    @feeleen
    Author

    btw even Environment.StackTrace, called from A's constructor in the code above, doesn't mention 'Main':

       at System.Environment.get_StackTrace()
       at A..ctor()
       at Program.Foo()
       at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
       at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext()
       at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox box, Boolean allowInlining)
       at System.Threading.Tasks.Task.RunContinuations(Object continuationObject)
       at System.Threading.Tasks.Task.FinishContinuations()
       at System.Threading.Tasks.Task.TrySetResult()
       at System.Threading.Tasks.Task.DelayPromise.CompleteTimedOut()
       at System.Threading.Tasks.Task.DelayPromise.<>c.<.ctor>b__1_0(Object state)
       at System.Threading.TimerQueueTimer.CallCallback(Boolean isThreadPool)
       at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool)
       at System.Threading.TimerQueue.FireNextTimers()
       at System.Threading.TimerQueue.AppDomainTimerCallback(Int32 id)
    
    
  3. KalleOlaviNiemitalo commented on Oct 23, 2021

    @KalleOlaviNiemitalo

    Similar features were requested in #14434 and #42684.

  4. added
    enhancement
    and removed
    untriaged
    on Oct 26, 2021
  5. added this to the 7.0.0 milestone on Oct 26, 2021
  6. tommcdon commented on Oct 26, 2021

    @tommcdon
    Member

    Adding @noahfalk @stephentoub for thoughts

  7. noahfalk commented on Oct 26, 2021

    @noahfalk
    Member

    I think the issues @KalleOlaviNiemitalo linked to do a good job showing some of the past exploration. While I'm sure there are still technical issues to work out for a solution, likely the biggest hurdle here is prioritization. When the issue first arose in 2015 async wasn't much used and the impact was low, but it is substantially larger now. This is probably a case where we've been slowly boiling the frog. For the past few releases we've been asking the BCL team for help on select areas of diagnostics and this might be a good one to get help on for .NET 7.

    cc @tarekgh

  8. tarekgh commented on Oct 26, 2021

    @tarekgh
    Member

    @stephentoub what are your thoughts around this issue? and what would be the way to fix it? any change would be needed from the compiler side?

    CC @jeffhandley @adamsitnik @carlossanlop @jozkee for awareness as owners of System.Threading.Tasks.

  9. stephentoub commented on Oct 26, 2021

    @stephentoub
    Member

    An Exception's stack trace contains the "async stack" because as it propagates from await to await, getting thrown and caught at every level, every throw appends additional information to the stack. Environment.StackTrace / new StackTrace() doesn't have the ability to propagate in such a manner. It has no notion of how it ended up asynchronously where it is or where it's going (the latter actually being what you get with an Exception stack trace, as it ends up recording in reverse the frames it propagates through as it's thrown and caught). There's no good way to provide a 100% "correct" stack trace here. The closest you'd come would probably be trying to walk the continuation chain from task to task, trying to simulate the flight an exception would take, but understanding all of the data structures along the way would not only be complicated, in some cases it'd be near impossible, as arbitrary things can hook up continuations to tasks (and runtime assistance would likely be required to find the start of the task chain). In short, it's possible something could be done here programmatically in corelib, but it would be far from easy or perfect.

  10. noahfalk commented on Oct 27, 2021

    @noahfalk
    Member

    but it would be far from easy or perfect.

    Agreed. I wasn't expecting we'd solve this in full generality. I was envisioning a solution that is perhaps constrained to only work on cases where all the Tasks are generated by the C# async keyword and continuations registered using await. (This is just an example, I'm very open to other suggestions on the effort vs. completeness vs. accuracy tradeoff too)

  11. modified the milestones: 7.0.0, Future on May 18, 2022
  12. Seabizkit commented on Jul 26, 2022

    @Seabizkit

    i dnt know this well enough to understand the technical challenges here.
    In my mind, if the code know where it need to go, there must be a route to follow, I mean in terms of the async and threading.
    I find it confusing that it doesn't know.

    Anyway was looking for this so i could query what method kick off another.
    Aka use case I was looking for, is in Ef core with DbCommandInterceptor it would be nice to be able to include the method (repo name which started the call. StackTrace really doesn't have the info needed.

    I would of thought this would already have been included for more complex debugging needs. Seems odd that you can view the call stack in VS but cant programmatically ask for it.

  13. RelativelyRandom commented on Oct 5, 2022

    @RelativelyRandom

    In my mind, if the code know where it need to go, there must be a route to follow, I mean in terms of the async and threading. I find it confusing that it doesn't know.

    @Seabizkit Here's an illustration of why this isn't as easy as it seems like it should be:

    private static async Task<int> ThrowingOperation()
    {
        await Task.Delay(1000);
        throw new InvalidOperationException("An exception.");
    }
    
    private static async Task<int> SomethingComplicated()
    {
        // Start doing something slow.
        Task<int> operationTask = ThrowingOperation();
    
        // Do something useful in the meantime.
        var intermediateResult = new Random().Next(20);
    
        if (intermediateResult < 10)
            return intermediateResult + await operationTask; // Option A
        else
            return intermediateResult - await operationTask; // Option B
    }
    
    private static async Task<int> CatchesTheException()
    {
        try
        {
            var notGoingToHappen = await SomethingComplicated();
            return notGoingToHappen;
        }
        catch(Exception e)
        {
            var trace = e.StackTrace;
            throw;
        }
    }
    

    The exception you catch in CatchesTheException will have a different stack trace depending on the value of intermediateResult. If it's less than 10, the stack trace will include option A, otherwise it will include option B. But ThrowingOperation cannot know where control flow will go next until the intermediate result is finished. Even worse, you can pass the same task to multiple methods which can all do an await on it and you'll get a different stack trace in all of those methods even though originally only a single exception was thrown.

    So in general async code cannot know where the result is going and it could be going to multiple places.

  14. mike7ang1rdz commented on May 3, 2023

    @mike7ang1rdz

    hello, I need this feature any workarounds?

  15. feeleen commented on Dec 2, 2023

    @feeleen
    Author

    I thik that we need just two things:

    1. compiler or runtime should capture & store the class & method where task was initially created. If it will be just one ugly line of text - ok (is it impossible? I dont think so)

    2. It should also capture the class & method where task was awaited from. If it will be just one ugly line of text - ok (if you meet "await" then just capture the place where it is called from by using caller info attributes or any other way. Is it impossible? I dont think so)

    These two things should be the mandatory part of any async stack trace at least in debug mode.

  16. rowi123 commented on May 11, 2024

    @rowi123

    i am also running into this problem
    for a specific bug i dump a tracktrace, but isn't so incomplete i can't use it
    i can see the stacktrace correctly in the debugger

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Diagnosticsenhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions