Skip to content

[API Proposal]: Include runtime async frames in Environment.StackTrace and System.Diagnostics.StackFrame #125417

Description

@tommcdon

Background

Customers often use logging to diagnose issues in production code. Environment.StackTrace is one of the possible ways to log current callstack and method location. Async v1 code often times be undiagnosable due to thread switches, for example calling Environment.StackTrace immediately after await Task.Delay would be resumed on a new thread, and so there would be no indication on how execution led to the current method.

Runtime Async (also known as Async V2) gives us a new opportunity to improve the scenario. Previously in Async V1, async execution state was tracked in Roslyn compiler-generated code, requiring decoding of async state machines to track caller/callee chains. Now with Async V2, the runtime tracks async execution and so we can now extract the resume locations and output this information as part of a synchronous callstack.

Motivation

Current behavior (without this change)

When a runtime async v2 method yields and is later resumed by the thread pool, Environment.StackTrace shows only what is physically on the stack:

at System.Environment.get_StackTrace()
at MyApp.MiddleMethod()
at System.Runtime.CompilerServices.YieldAwaitable+YieldAwaiter.RunAction(Object)
at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading.PortableThreadPool+WorkerThread.WorkerDoWork(...)
at System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()
at System.Threading.Thread.StartCallback()

The logical callers — which async methods are awaiting MiddleMethod — are completely absent. A developer has no way to determine why MiddleMethod is running.

Desired behavior

at System.Environment.get_StackTrace()
at MyApp.MiddleMethod() in MyApp.cs:line 42
at MyApp.OuterMethod() in MyApp.cs:line 30       ← continuation frame
at MyApp.EntryPoint() in MyApp.cs:line 15        ← continuation frame

Internal dispatch machinery (DispatchContinuations, thread pool frames) is hidden, and the logical async caller chain is reconstructed from the runtime's continuation data.

Why this matters

  • Debugging: Log files with Environment.StackTrace are a useful diagnostic tool. Without the async caller chain, developers cannot trace the origin of a call.
  • Parity with Exception stack traces
  • Observability tooling: APM tools, logging frameworks, and profilers that consume StackTrace objects need the logical call chain to build meaningful traces.

API Proposal

No API changes are suggested - this is changing behavior of an existing API to provide more information. API's affected are:

  • System.Diagnostics.StackFrame
  • System.Diagnostics.StackTrace.ctor
  • System.Environment.StackTrace

Draft PR with proposed changes is here: #125396

API Usage

    static void PrintStackTrace()
    {
        // Get the current stack trace as a string
        string stackTrace = Environment.StackTrace;

        Console.WriteLine("Current Stack Trace:");
        Console.WriteLine(stackTrace);
    }

Alternative Designs

We could consider adding overloads that make the behavior opt-in or opt-out

Risks

Including runtime async frames might unexpectedly slow down performance for those that log callstacks in production scenarios, or bloat the log files themselves causing an extra expense on log storage.
Risk is mitigated by:

  1. Runtime async is currently opt-in at the application level (at the time of writing in .NET 11)
  2. Diagnostic benefits should outweigh performance or log size concerns. To mitigate this risk, the feature should include an opt-out app config switch to revert to fully non-async callstacks. We can also consider API overloads as well depending on feedback.

Activity

  1. added this to the 11.0.0 milestone on Mar 10, 2026
  2. self-assigned this
    on Mar 10, 2026
  3. added theissue type on Mar 10, 2026
  4. added
    enhancement
    api-suggestion
    on Mar 10, 2026
  5. dotnet-policy-service commented on Mar 10, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @steveisok, @tommcdon, @dotnet/dotnet-diag
    See info in area-owners.md if you want to be subscribed.

  6. MihuBot commented on Mar 10, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  7. added
    api-suggestion
    and removed
    api-suggestion
    on Mar 11, 2026
  8. noahfalk commented on Mar 11, 2026

    @noahfalk
    Member

    I like that we are doing this :D A variety of questions trying to dig more into the details of the design...

    1. The APIs affected didn't mention System.Diagnostics.StackTrace.ctor, is that included?
    2. If a runtime async method has a continuation that is an AsyncV1 Task does the stack chain through?
    3. If a V1 async task is at the leaf of the stack does that get included in the stack trace?
    4. If there are multiple continuations pending on the same frame, what do we show in the stack? Does it depend on the kind of continuation objects that are registered?
    5. Does the stack capture anything about synchronous calls that created the async Task or that might be waiting on it? (Task.Start(), Task.Wait(), Task.Run())
  9. added and removed
    api-suggestion
    on Mar 11, 2026
  10. tommcdon commented on Mar 17, 2026

    @tommcdon
    MemberAuthor

    The APIs affected didn't mention System.Diagnostics.StackTrace.ctor, is that included?

    Added to the list

    If a runtime async method has a continuation that is an AsyncV1 Task does the stack chain through?

    Only runtime async v2 continuation chains are shown in the stack - no async v1 state machines are decoded. For example:

    // ===== Mixed v2 → v1 → v2 chain =====
    
    async Task<string> V2_Outer()
    {
        return await V1_Middle();
    }
    
    [RuntimeAsyncMethodGeneration(false)] // Force v1 (state machine) generation
    async Task<string> V1_Middle()
    {
        return await V2_Inner();
    }
    
    async Task<string> V2_Inner()
    {
        await Task.Yield(); // Force suspension
        return Environment.StackTrace;
    }
    
    V2_Outer().GetAwaiter().GetResult();

    Would output the following stack:

    at System.Environment.get_StackTrace()
    at Program.V2_InnerMethod() in Program.cs:line XYZ
    at System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.RunAction(Object state)
    at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
    at System.Threading.ThreadPoolWorkQueue.Dispatch()
    at System.Threading.PortableThreadPool.WorkerThread.WorkerDoWork(PortableThreadPool threadPoolInstance)
    at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
    at System.Threading.Thread.StartCallback()
    

    If a V1 async task is at the leaf of the stack does that get included in the stack trace?

    Same as the above - if the left (current) frame is an async v1 state machine, we do not decode it and will simply show the synchronous stack on the thread. For example:

    // ===== V1 Leaf - v2 → v2 → v1 chain =====
    
    async Task<string> V2_Outer()
    {
        return await V2_Middle();
    }
    
    async Task<string> V2_Middle()
    {
        return await V1_Leaf();
    }
    
    [RuntimeAsyncMethodGeneration(false)] // Force v1 (state machine) generation
    async Task<string> V1_Leaf()
    {
        await Task.Yield();
        return Environment.StackTrace;
    }
    
    V2_Outer().GetAwaiter().GetResult();

    Would output the following stack:

    at System.Environment.get_StackTrace()
    at Program.V1_Leaf() in Program.cs:line XYZ
    at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.ExecutionContextCallback(Object s)
    at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, 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.ExecuteFromThreadPool(Thread threadPoolThread)
    at System.Threading.ThreadPoolWorkQueue.Dispatch()
    at System.Threading.PortableThreadPool.WorkerThread.WorkerDoWork(PortableThreadPool threadPoolInstance)
    at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
    at System.Threading.Thread.StartCallback()
    

    If there are multiple continuations pending on the same frame, what do we show in the stack? Does it depend on the kind of continuation objects that are registered?

    Continuation chains should be single linked lists. It is possible that there are "nested" wait chains on the same thread. For that case, we only show the first one in the list. I experimented it trying to show "nested" continuations but felt it ended up being more confusing than helpful.

    For example:

    async Task Run()
    {
        TaskCompletionSource tcs = new TaskCompletionSource();
        Task t = BarCaller(tcs.Task);
        Task t2 = FooCaller(tcs);
        await Task.WhenAll(t, t2);
    }
    
    async Task FooCaller(TaskCompletionSource tcs)
    {
        await Task.Yield();
        Console.WriteLine("FooCaller calling Foo...");
        await Foo(tcs);
    }
    
    async Task Foo(TaskCompletionSource tcs)
    {
        //await Task.Yield();
        Console.WriteLine("Foo delay...");
        await Task.Delay(1);
        Console.WriteLine("Foo setting tcs...");
        tcs.SetResult();
    }
    
    async Task BarCaller(Task task)
    {
        Console.WriteLine("BarCaller yielding...");
        await Task.Yield();
        Console.WriteLine("BarCaller calling Bar...");
        await Bar(task);
    }
    
    async Task Bar(Task task)
    {
        Console.WriteLine("Bar yielding...");
        await Task.Yield();
        Console.WriteLine("Bar awaiting the tsc task...");
        await task;
        Console.WriteLine("Bar dumping the stack...");
        Console.WriteLine(Environment.StackTrace);
    }
    
    Run().GetAwaiter().GetResult();

    Would output:

    ...
    Bar dumping the stack...
       at System.Environment.get_StackTrace()
       at AsyncTest_tcs.Bar(Task task) in Program.cs:line XYZ1
       at AsyncTest_tcs.BarCaller(Task task) in Program.cs:line XYZ2
       at AsyncTest_tcs.FooCaller(TaskCompletionSource tcs) in Program.cs:line XYZ3
    

    Does the stack capture anything about synchronous calls that created the async Task or that might be waiting on it? (Task.Start(), Task.Wait(), Task.Run())

    The feature as it is proposed today treats existing async V1 task and state machine decoding as out of scope, so we only display what is included in the runtime async continuation data which does not include calls to Task.Start/Wait/Run.

  11. noahfalk commented on Mar 18, 2026

    @noahfalk
    Member

    Thanks Tom!

    Async V1 handling

    The feature as it is proposed today treats existing async V1 task and state machine decoding as out of scope

    I'd be curious to dig into this a bit more - its not obvious to me that it should be out of scope. Certainly there would be more work involved so I don't want to expand the scope cavalierly, but a few considerations that push me in that direction:

    • Changing Environment.StackTrace is a breaking change that will probably require some .NET developers to make adjustments to their application code if they were parsing it or had certain UX expectations around it. If we think devs will want Async V1 support ideally we do it all at once rather than spreading breaking changes over multiple releases.
    • In the short term many libraries might continue to use Async V1 because the code hasn't been recompiled to target V2.
    • Longer term I'm not aware we have any plan to completely phase out Async V1 so it would continue to be a rough edge in the feature indefinitely. The first example that came to mind is code that uses Task.WhenAny/WhenAll. I know there are plenty of other custom task types out there though I'm not sure how many of them are likely to run app developer code while they are on the async stack.

    I think there are varying degrees of support we could have for V1. For example we could probably trace a continuation chain through V1 tasks without rendering anything into the stacktrace, or we could render some basic information like a method name, or we could really dig into it and disassemble the Async V1 state machine to infer an IL offset -> file info. IMO its worth looking into. (@jkotas, @stephentoub, @davidfowl - I'd be glad to get your perspectives on this)

    When does synchronous dispatch logic appear

    Another question that would be good to dig into... what synchronous frames get shown on the stack? The initial example in the issue showed only synchronous frames that were closer to the leaf than the most recent async frame:

    at System.Environment.get_StackTrace()
    at MyApp.MiddleMethod() in MyApp.cs:line 42
    at MyApp.OuterMethod() in MyApp.cs:line 30 ← continuation frame
    at MyApp.EntryPoint() in MyApp.cs:line 15 ← continuation frame

    Would output the following stack:

    However in this V2_InnerMethod example from above, V2_InnerMethod is implemented with async V2 but it is showing all of the synchronous dispatch logic in the stack. If I nievely imagine the pattern shown in the first example and apply it here then I wouldn't expect the YieldAwaitable frame or anything below it to show up:

    at System.Environment.get_StackTrace()
    at Program.V2_InnerMethod() in Program.cs:line XYZ
    at System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.RunAction(Object state)
    at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
    at System.Threading.ThreadPoolWorkQueue.Dispatch()
    at System.Threading.PortableThreadPool.WorkerThread.WorkerDoWork(PortableThreadPool threadPoolInstance)
    at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
    at System.Threading.Thread.StartCallback()

    I'm guessing that we are rendering the stacks differently depending on whether control entered at the start of the function or what dispatcher was responsible for resuming after an await. That feels like unnecessary implementation detail we'd be better off not leaking into the user experience if we can help it.

    Nested waits

    It is possible that there are "nested" wait chains on the same thread. For that case, we only show the first one in the list. I experimented it trying to show "nested" continuations but felt it ended up being more confusing than helpful.

    I agree. I think it is a cleaner representation of the async abstraction to follow a single async continuation chain to its root, disregarding the dispatch logic or outer dispatchers that might be present on the same OS thread stack.

    opt-in/out

    We could consider adding overloads that make the behavior opt-in or opt-out

    One place that might fit well is new overloads or options on the StackTrace constructor. Additionally a config switch that lets folks preserve the current Environment.StackTrace behavior seems like a cheap and helpful mitigation for folks who don't want the async-aware behavior.

  12. 6 remaining items

  13. tommcdon commented on Apr 9, 2026

    @tommcdon
    MemberAuthor

    Truncate the stack when encountering a Task blocking method like Task.Wait ...
    The alternative where we opportunistically include synchronous stack frames when they are present on the stack would print:

    @noahfalk I think this is an interesting idea and have prototyped it here - tommcdon@4ace763. It supports a config knob (DOTNET_HideAsyncDispatchFrames) where we can switch between 3 modes:

    • 0 = show all frames (no filtering)
    • 1 = hide all non-async frames below first async frame (default)
    • 2 = keep non-async frames between async frames, truncate trailing

    The commit can be applied to our draft PR here if we feel this is the right direction: #125396. I feel we could include this change with a default we agree upon.

  14. jkotas commented on Apr 10, 2026

    @jkotas
    Member

    Have you tried the different options on real-world code? Which one of these options provides the best experience in your opinion?

    If we want to have different options, would it make sense to surface them as APIs?

    I would stay away from configuration knobs as the long-term solution. It is ok to have the configuration knobs as a temporary mitigation if the change in defaults is too breaking.

  15. noahfalk commented on Apr 10, 2026

    @noahfalk
    Member

    I would stay away from configuration knobs as the long-term solution

    I believe this was more to make it easier for users (internal or external) to give us feedback on different alternatives prior to deciding on the final .NET 11 behavior. Separately I do also think a config knob that lets people opt-out of the breaking change at least for a while could be pretty useful.

    If we want to have different options, would it make sense to surface them as APIs?

    IMO some options on the StackTrace API constructor would probably be helpful.

  16. noahfalk commented on Apr 10, 2026

    @noahfalk
    Member

    @timcassell - thanks for the feedback :)

    It's expensive! Every async yield captures the current stacktrace, and that ain't cheap.

    Yeah, even with access to low-level runtime infrastructure that can do that somewhat more efficiently we are still only proposing to preserve the frames marked as async across the await points. Capturing the full synchronous callstack at each await just in case the code requests a stacktrace in the future looks like too high of a performance penalty relative to its diagnostic value.

  17. tommcdon commented on Apr 10, 2026

    @tommcdon
    MemberAuthor

    Have you tried the different options on real-world code?

    I have tried various test applications but not real world yet.

    Which one of these options provides the best experience in your opinion?

    Personally, I slightly lean towards the original proposal as it avoids information loss, which can be useful in the full-synchronous case. Hiding of frames drives consistency, but my preference would be to see the information that is available at that point in time. Logging is often used in production for diagnostics, so displaying all available data might be the optimal choice. I am open to trying the option where we hide frames (shipped via a preview) and then changing the default based of customer feedback.

  18. timcassell commented on Apr 10, 2026

    @timcassell

    Capturing the full synchronous callstack at each await just in case the code requests a stacktrace in the future looks like too high of a performance penalty relative to its diagnostic value.

    It could be a knob or API to enable the full trace, so the default performance doesn't suffer, and developers who really need it can get all the info. That's how I currently handle it in my lib.

  19. tommcdon commented on Apr 12, 2026

    @tommcdon
    MemberAuthor

    One place that might fit well is new overloads or options on the StackTrace constructor.
    It could be a knob or API to enable the full trace

    @noahfalk @timcassell @jkotas Here is a proposal adding SttraceTrace constructor and Env.StackTrace overloads. Is this something we might be interested in adding?

    namespace System
    {
        public static class Environment
        {
            /// <summary>
            /// Returns a string representation of the current call stack, with the specified
            /// async frame behavior controlling how runtime async v2 frames are presented.
            /// </summary>
            public static string GetStackTrace(StackTraceAsyncBehavior asyncBehavior)
        }
    }
    
    namespace System.Diagnostics
    {
        public class StackTrace
        {
            /// <summary>
            /// Constructs a stack trace from the current location with the specified
            /// async frame behavior.
            /// </summary>
            public StackTrace(StackTraceAsyncBehavior asyncBehavior);
    
            /// <summary>
            /// Constructs a stack trace from the current location with the specified
            /// async frame behavior.
            /// </summary>
            public StackTrace(int skipFrames, bool fNeedFileInfo, StackTraceAsyncBehavior asyncBehavior);
        }
    
        /// <summary>
        /// Controls how async frames are handled during stack trace capture.
        /// </summary>
        public enum StackTraceAsyncBehavior
        {
            /// <summary>
            /// Walk async continuations and hide non-async frames below the first
            /// runtime async frame so pre-await and post-await traces look identical.
            /// This is the default.
            /// </summary>
            Default = 0,
    
            /// <summary>
            /// Walk async continuations but show all physical frames.
            /// Pre-await traces include synchronous callers; post-await traces do not.
            /// </summary>
            ShowAllFrames = 1,
    
            /// <summary>
            /// Walk async continuations, keep non-async frames between async methods,
            /// but truncate trailing non-async frames below the last async frame.
            /// </summary>
            TruncateTrailing = 2,
    
            /// <summary>
            /// No async continuation stitching. Returns only the physical call stack.
            /// This is the fastest option — skips continuation chain walking entirely.
            /// </summary>
            PhysicalOnly = 3,
        }
    }
  20. timcassell commented on Apr 12, 2026

    @timcassell

    I don't think a StackTrace ctor argument is enough for what I'm asking for. It will need to be a global property for async yields to capture the current trace, and probably a new API for things like custom events to capture the trace when a listener is added similar to ExecutionContext (so not only async/await can get full traces, but any async calls). Maybe all that is too much, idk.

  21. DamirLisak commented on Jun 5, 2026

    @DamirLisak

    If I may take the liberty of bringing up this issue #80555 again here, given that it is closely related to this stack trace API proposal.

    I would also like to add a comment regarding @jkotas question Have you tried the different options on real-world code?:

    When dealing with stateful applications that feature a high degree of multithreading and dynamically load software components via orchestration at runtime, the risk of deadlocks during production is significantly higher compared to self-contained applications. Consequently, for such systems, it is crucial to be able to analyze the root causes of deadlocks - something that is only possible if one can examine the stacks of all threads, rather than just the current thread's stack.
    Third-party diagnostic tools are of little help here, as the ability to recognize and read object states - and correlate them with thread stack information - exists only within the application itself.
    For this reason, I believe it is necessary to have a method or property that outputs the full stacks of all threads - such as Environment.StackTraceAll or something similar.
    Nevertheless, I also think developers should have the option to decide for themselves exactly which threads to analyze. Therefore, in my view, the best solution would be to reintroduce the suspend and resume functionality that existed in .NET Framework 4 into .NET Core.

  22. modified the milestones: 11.0.0, 12.0.0 on Jul 28, 2026
  23. timcassell commented on Oct 15, 2026

    @timcassell

    After working with Claude to refine my experiment, I retract my request. It turns out that capturing the full history ends up being too much irrelevant information in a long await chain, and async scheduling loops could even cause a memory leak. It might still be useful to have the synchronous StackTrace of whoever created the outermost Task, but probably not useful enough to justify the cost.

  24. pcshrosbree commented on Nov 11, 2026

    @pcshrosbree
    Contributor

    Could StackFrame get a read-only property, such as bool IsAsyncContinuation, that says whether a frame came from the physical stack walk or was added from the async continuation chain? The proposed StackTraceAsyncBehavior would choose the behavior for each capture, and the suggested marker lines would show the boundary in the string. A tool that reads StackFrame objects instead of the string needs the same information for each frame.

    In CoreCLR, the runtime marks continuation frames internally with STEF_CONTINUATION, but StackFrameHelper does not pass that flag to managed code. Exception stack traces that unwind through runtime-async continuations already contain such frames, so the gap exists there too.

    The runtime itself treats the two kinds of frame differently when it maps a native offset to IL. In DebugStackTrace::Element::InitPass2 (src/coreclr/vm/debugdebugger.cpp), an offset is moved back by STACKWALK_CONTROLPC_ADJUST_OFFSET before the IL lookup only if it is positive, was not already adjusted, and does not belong to a continuation frame:

    bool fAdjustOffset = (this->flags & STEF_IP_ADJUSTED) == 0 && this->dwOffset > 0 && !(this->flags & STEF_CONTINUATION);

    I built PR #125396 at 7e2cfb7b13 locally (Release, linux-x64) and called new StackTrace(false) in Inner after await Task.Yield(), in an Outer → Middle → Inner chain. With the PR's default DOTNET_StackTraceAsyncBehavior setting, the trace contains the physical frame Inner, followed by the continuation frames Middle and Outer. No public StackFrame member identifies which frames came from the continuation chain. I mapped GetNativeOffset() to IL with the MethodILToNativeMap events. For Inner, the offset is a return address: it maps to the IL after the StackTrace constructor call, and offset − 1 gives the IL offset that GetILOffset() reports. For Middle and Outer, the offset maps to the IL offset of the awaiting call, and offset − 1 falls in a range with no IL mapping.

    A tool that applies the same return-address adjustment to every GetNativeOffset() would therefore mis-map the continuation frames in this probe, and nothing on the frame tells it which frames to treat differently. I also ran a chain of the same shape that throws after await Task.Yield(), on main at 36e205e and at the PR's merge base. Its exception traces contain the two continuation frames too, and their offsets also map directly to the IL offsets of the awaiting calls.

    I read the CoreCLR code at main c772c4c690.

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

Metadata

Metadata

Assignees

Labels

area-Diagnostics-coreclrenhancementruntime-async

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions