Repository navigation
Description
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.StackTraceare 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
StackTraceobjects 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:
- Runtime async is currently opt-in at the application level (at the time of writing in .NET 11)
- 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
dotnet-policy-service commentedon Mar 10, 2026
Tagging subscribers to this area: @steveisok, @tommcdon, @dotnet/dotnet-diag
See info in area-owners.md if you want to be subscribed.
MihuBot commentedon Mar 10, 2026
I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):
new StackTrace()inside async methods -> Useless, Lack of frames with sync caller method (initiator) #60764noahfalk commentedon Mar 11, 2026
I like that we are doing this :D A variety of questions trying to dig more into the details of the design...
System.Diagnostics.StackTrace.ctor, is that included?tommcdon commentedon Mar 17, 2026
Added to the list
Only runtime async v2 continuation chains are shown in the stack - no async v1 state machines are decoded. For example:
Would output the following stack:
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:
Would output the following stack:
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:
Would output:
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.
noahfalk commentedon Mar 18, 2026
Thanks Tom!
Async V1 handling
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:
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:
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:
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
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
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.
6 remaining items
tommcdon commentedon Apr 9, 2026
@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:
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.
jkotas commentedon Apr 10, 2026
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.
noahfalk commentedon Apr 10, 2026
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.
IMO some options on the StackTrace API constructor would probably be helpful.
noahfalk commentedon Apr 10, 2026
@timcassell - thanks for the feedback :)
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.
tommcdon commentedon Apr 10, 2026
I have tried various test applications but not real world yet.
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.
timcassell commentedon Apr 10, 2026
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.
tommcdon commentedon Apr 12, 2026
@noahfalk @timcassell @jkotas Here is a proposal adding SttraceTrace constructor and Env.StackTrace overloads. Is this something we might be interested in adding?
timcassell commentedon Apr 12, 2026
I don't think a
StackTracector 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 toExecutionContext(so not only async/await can get full traces, but any async calls). Maybe all that is too much, idk.DamirLisak commentedon Jun 5, 2026
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.StackTraceAllor 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.
timcassell commentedon Oct 15, 2026
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.
pcshrosbree commentedon Nov 11, 2026
Could
StackFrameget a read-only property, such asbool IsAsyncContinuation, that says whether a frame came from the physical stack walk or was added from the async continuation chain? The proposedStackTraceAsyncBehaviorwould choose the behavior for each capture, and the suggested marker lines would show the boundary in the string. A tool that readsStackFrameobjects instead of the string needs the same information for each frame.In CoreCLR, the runtime marks continuation frames internally with
STEF_CONTINUATION, butStackFrameHelperdoes 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 bySTACKWALK_CONTROLPC_ADJUST_OFFSETbefore the IL lookup only if it is positive, was not already adjusted, and does not belong to a continuation frame:I built PR #125396 at
7e2cfb7b13locally (Release, linux-x64) and callednew StackTrace(false)inInnerafterawait Task.Yield(), in anOuter→Middle→Innerchain. With the PR's defaultDOTNET_StackTraceAsyncBehaviorsetting, the trace contains the physical frameInner, followed by the continuation framesMiddleandOuter. No publicStackFramemember identifies which frames came from the continuation chain. I mappedGetNativeOffset()to IL with theMethodILToNativeMapevents. ForInner, the offset is a return address: it maps to the IL after theStackTraceconstructor call, and offset − 1 gives the IL offset thatGetILOffset()reports. ForMiddleandOuter, 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 afterawait Task.Yield(), on main at36e205eand 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.