You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
new StackTrace() inside async methods -> Useless, Lack of frames with sync caller method (initiator) #60764
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
usingSystem;usingSystem.Diagnostics;usingSystem.Runtime.CompilerServices;usingSystem.Linq;usingSystem.Threading.Tasks;classProgram{staticvoidMain(){Foo().GetAwaiter().GetResult();}staticasyncTaskFoo(){awaitTask.Delay(100);Aa=new();}}publicclassA{publicA(){Console.WriteLine("In this stackTrace we know nothing about 'Main':");newStackTrace().GetFrames().ToList().ForEach(x =>Console.WriteLine(x.GetMethod()?.Name));Console.WriteLine(Environment.NewLine);Console.WriteLine("Here, in exception stacktrace we will see 'Main':");thrownewException();}}
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?
Reacted by oof, Ruslan Batkaev and Nirmal Guru
Activity
ghost added
untriagedNew issue has not been triaged by the area owner
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)
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.
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.
Reacted by Tarek Mahmoud Sayed, Tom McDonald, Joe4evr, Mislav Čovran and Colin McCullough
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)
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.
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.
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)
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.
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
Activity
feeleen commentedon Oct 22, 2021
btw even
Environment.StackTrace, called from A's constructor in the code above, doesn't mention 'Main':KalleOlaviNiemitalo commentedon Oct 23, 2021
Similar features were requested in #14434 and #42684.
tommcdon commentedon Oct 26, 2021
Adding @noahfalk @stephentoub for thoughts
noahfalk commentedon Oct 26, 2021
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
tarekgh commentedon Oct 26, 2021
@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.
stephentoub commentedon Oct 26, 2021
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.noahfalk commentedon Oct 27, 2021
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)
Seabizkit commentedon Jul 26, 2022
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.
RelativelyRandom commentedon Oct 5, 2022
@Seabizkit Here's an illustration of why this isn't as easy as it seems like it should be:
The exception you catch in
CatchesTheExceptionwill have a different stack trace depending on the value ofintermediateResult. If it's less than 10, the stack trace will include option A, otherwise it will include option B. ButThrowingOperationcannot 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 anawaiton 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.
mike7ang1rdz commentedon May 3, 2023
hello, I need this feature any workarounds?
feeleen commentedon Dec 2, 2023
I thik that we need just two things:
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)
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.
rowi123 commentedon May 11, 2024
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