Why does Visual Studio break on a caught exception thrown inside an IAsyncEnumerable?
Your try/catch around CountAsync or ToListAsync works, but Visual Studio still stops with Exception User-Unhandled. On .NET 9+ the debugger breaks when an exception leaves your async code and is caught by framework code, and the async iterator's GetResult is DebuggerHidden. Why it happens, verified on .NET 11.0.0, and four ways to stop it.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
The exception is not escaping your try/catch. Run the program without the debugger (Ctrl+F5) and the catch block runs every time. What you are seeing is the Visual Studio debugger’s “async user-unhandled” break, enabled by default for .NET 9 and later projects: when an exception passes through your async code and is then caught by framework code, Visual Studio stops as if it were unhandled. A LINQ operator such as CountAsync, ToListAsync or FirstAsync over your async IAsyncEnumerable<T> is exactly that framework code, so the break fires even though your own catch is further up the chain. Press F5 to continue, untick “Break when this exception type is user-unhandled” in the Exception Helper, or consume the sequence with await foreach in your own method. This post explains the mechanism with a reproduction on .NET 11.0.0 and the System.Linq.AsyncEnumerable that ships in the box since .NET 10.
The repro from the question
The pattern comes from a Stack Overflow question asked in Visual Studio 2026: an async iterator awaits a helper that eventually throws, Main wraps the whole thing in a try/catch, and the debugger still reports the exception as unhandled. Here is a self-contained version:
// .NET 11.0.0 (SDK 11.0.100), C# 15, net11.0 console app, Debug configuration
int counter = 0;
async Task<int> GenerateValue()
{
await Task.Delay(10);
if (counter == 5) throw new InvalidOperationException("boom at 5");
return counter++;
}
async IAsyncEnumerable<int> GetValues()
{
while (counter < 100)
{
var value = await GenerateValue();
yield return value;
}
}
try
{
await GetValues().CountAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught: {ex.GetType().Name}: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
Run without a debugger on macOS arm64 with runtime 11.0.0 (dotnet run -c Debug), the catch block runs and prints this (paths shortened):
Exception caught: InvalidOperationException: boom at 5
at Program.<>c__DisplayClass0_0.<<<Main>$>g__GenerateValue|0>d.MoveNext() in /repro/Program.cs:line 10
--- End of stack trace from previous location ---
at Program.<>c__DisplayClass0_0.<<<Main>$>g__GetValues|1>d.MoveNext() in /repro/Program.cs:line 18
--- End of stack trace from previous location ---
at Program.<>c__DisplayClass0_0.<<<Main>$>g__GetValues|1>d.System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult(Int16 token)
at System.Linq.AsyncEnumerable.<CountAsync>g__Impl|37_0[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.<CountAsync>g__Impl|37_0[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
at Program.<Main>$(String[] args) in /repro/Program.cs:line 27
So the language and the runtime do the right thing. The exception travels from GenerateValue into the iterator, out of the iterator through GetResult, through CountAsync, and into Main’s catch. The interesting part is the two frames in the middle.
Why the debugger calls it user-unhandled
Visual Studio has always had three ways to stop on a managed exception: first-chance (you ticked the type in Exception Settings), unhandled (nobody catches it), and user-unhandled. The last one only exists with Just My Code on, and it means: the exception went through user code and the catch handler that ends up handling it lives in non-user code.
For synchronous code that rule has existed for years. For async code it did not work, because every async Task method compiles to a state machine whose MoveNext has an implicit catch that stores the exception into the returned task. To the debugger that implicit catch is a catch in user code, so the exception looked handled the moment it left your method, and whatever framework code later awaited and rethrew it was hidden by Just My Code. The Visual Studio team fixed this in 2024: as described in Break for Async User-Unhandled exceptions in the Visual Studio Debugger (Anders Sundheim, September 10, 2024), the debugger now keeps following the exception object after that implicit catch. If non-user code later rethrows it and catches it, the debugger breaks. The feature applies to .NET 9 and newer projects only, which is why the same code under .NET 8 never stopped.
Now look at what counts as user code in the repro. I compiled it with SDK 11.0.100 and listed the attributes on the compiler-generated iterator class <<<Main>$>g__GetValues|1>d with reflection:
MoveNext: (none)
SetStateMachine: DebuggerHiddenAttribute
IAsyncEnumerable<Int32>.GetAsyncEnumerator: DebuggerHiddenAttribute
IAsyncEnumerator<Int32>.MoveNextAsync: DebuggerHiddenAttribute
IAsyncEnumerator<Int32>.get_Current: DebuggerHiddenAttribute
IValueTaskSource<Boolean>.GetResult: DebuggerHiddenAttribute
IValueTaskSource<Boolean>.GetStatus: DebuggerHiddenAttribute
IValueTaskSource<Boolean>.OnCompleted: DebuggerHiddenAttribute
IAsyncDisposable.DisposeAsync: DebuggerHiddenAttribute
Only MoveNext, the method that holds your iterator body, is user code. Everything the consumer calls to drive the iterator is marked [DebuggerHidden], and Just My Code treats hidden methods as non-user code. That includes IValueTaskSource<bool>.GetResult, the method that rethrows the exception the iterator stored when its body faulted.
And CountAsync is framework code too. Running the same program printed where AsyncEnumerable comes from:
CountAsync lives in: System.Linq.AsyncEnumerable 11.0.0.0 @ ~/.dotnet11/shared/Microsoft.NETCore.App/11.0.0/System.Linq.AsyncEnumerable.dll
Since .NET 10, System.Linq.AsyncEnumerable is part of the shared framework (it was previously the community System.Linq.Async package), so it is optimized, ships without your symbols, and is non-user code for Just My Code. The full trip from the debugger’s point of view is:
GenerateValuethrows. Its implicit async catch (user code) stores the exception in itsTask<int>.- The iterator’s
MoveNextawaits that task, the exception is rethrown and caught by the iterator’s own implicit catch (user code), which faults the pendingMoveNextAsyncresult. CountAsync(non-user) awaitsMoveNextAsync, which callsGetResult([DebuggerHidden], non-user). The exception is rethrown and caught byCountAsync’s state machine. Non-user code caught an exception that came out of user code: that is the break.
Your catch in Main only gets the exception after step 3, by which point the debugger has already decided. The Visual Studio blog post also documents where it stops: not on your frame, but on the frame below it where the exception was rethrown and caught in non-user code, which shows up as [External Code]. The debugger fills in synthetic [Exception] frames for your async methods and tries to recover their state, but the original frames are gone, so some locals (reference-type locals, and value types that contain references) may already be nulled out.
Proof that consuming it yourself changes the picture
The same iterator consumed with await foreach in Main produces a different stack:
// .NET 11.0.0, C# 15
counter = 0;
try
{
int n = 0;
await foreach (var v in GetValues()) n++;
}
catch (Exception ex)
{
Console.WriteLine($"await foreach caught: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
await foreach caught: boom at 5
at Program.<>c__DisplayClass0_0.<<<Main>$>g__GenerateValue|0>d.MoveNext() in /repro/Program.cs:line 10
--- End of stack trace from previous location ---
at Program.<>c__DisplayClass0_0.<<<Main>$>g__GetValues|1>d.MoveNext() in /repro/Program.cs:line 18
--- End of stack trace from previous location ---
at Program.<>c__DisplayClass0_0.<<<Main>$>g__GetValues|1>d.System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult(Int16 token)
at Program.<Main>$(String[] args) in /repro/Program.cs:line 39
No framework frame sits between GetResult and your catch. The await foreach loop is compiled into Main’s own state machine, so the catch that receives the rethrown exception is your explicit catch (Exception ex) in user code, and the user-unhandled condition is never met.
A limit on what was checked here: both stacks above come from real runs on .NET 11.0.0, and the attribute list comes from the compiled assembly. The Visual Studio break itself was not reproduced for this post, because that needs Visual Studio on Windows. The explanation of when the debugger breaks is taken from Microsoft’s documentation of the feature, applied to the frames these runs show.
Four ways to stop the break
Pick based on whether you want to keep the feature for other exceptions.
Continue, or untick the box for that exception type
The cheapest fix is to press F5. The program continues and your catch runs. If the break gets annoying for one exception type, the Exception Helper popup has a “Break when this exception type is user-unhandled” checkbox; untick it. The same setting lives in Debug > Windows > Exception Settings: per Manage exceptions with the debugger, right-click a column header and enable Show Columns > Additional Actions (the command only appears when Just My Code is on), then right-click an exception and choose Continue When Unhandled in User Code. You can apply it to a single type or a whole category such as Common Language Runtime Exceptions.
This is the right answer when the exception is expected: a validation failure, a cancellation, a “not found” your caller handles.
Consume the sequence in your own code
If the operator is trivial, write it yourself. CountAsync is a three-line await foreach:
// .NET 11.0.0, C# 15
static async Task<int> CountAsync<T>(IAsyncEnumerable<T> source, CancellationToken ct = default)
{
int count = 0;
await foreach (var _ in source.WithCancellation(ct))
count++;
return count;
}
Now no non-user code sits between your iterator and a user-code catch. Note the catch still has to be in user code: if this helper does not catch and its caller is user code, the exception travels from one user frame to the next and the debugger has nothing to report. Do not rewrite every LINQ call this way just to silence the debugger. It is worth it when the hot path of your debugging session goes through one operator and the break keeps stopping you.
Turn the feature off globally
The blog post documents an engine switch. From a Visual Studio Developer Command Prompt:
vsregedit set local hklm Debugger\EngineSwitches DisableBreakForAsyncUserUnhandled dword 1
This brings back the pre-.NET 9 behavior for async code while keeping user-unhandled breaks for synchronous code. Turning off Just My Code entirely (Tools > Options > Debugging > General > Enable Just My Code) also removes the break, but it removes the whole user-unhandled category with it and makes stepping noisier, so it is the blunt option.
Library authors: [DebuggerDisableUserUnhandledExceptions]
.NET 9 added DebuggerDisableUserUnhandledExceptionsAttribute and Debugger.BreakForUserUnhandledException(Exception) for frameworks that call user code and handle its exceptions on purpose (ASP.NET Core uses them). The attribute targets methods only, and the debugger will not break on user-unhandled exceptions caught by a method that carries it, unless that method calls BreakForUserUnhandledException:
// .NET 9+ (checked here against .NET 11.0.0)
using System.Diagnostics;
using System.Runtime.CompilerServices;
[MethodImpl(MethodImplOptions.NoInlining)]
[DebuggerDisableUserUnhandledExceptions]
static async Task InvokeUserCode(Func<Task> userCode, Func<Exception, bool> isExpected)
{
try
{
await userCode();
}
catch (Exception ex)
{
if (isExpected(ex))
return; // handled, no break
Debugger.BreakForUserUnhandledException(ex); // unexpected: break here
throw;
}
}
This does not help in the CountAsync case from application code: the method that catches is CountAsync’s state machine inside the runtime, and you cannot put an attribute on it. It is the tool for the code that sits where CountAsync sits, a dispatcher, a pipeline, a message handler in your own library that consumes user-supplied iterators and deliberately turns failures into results.
What about the catch-and-rethrow workaround?
The asker found that wrapping the await GenerateValue() call inside the iterator in try { ... } catch (Exception) { throw; } made the break go away. That observation comes from their Visual Studio 2026 session and was not reproduced here. Under the documented model the rethrown exception still leaves the iterator through the same [DebuggerHidden] GetResult into the same non-user CountAsync, so there is no documented reason it should change the outcome, and it is not something to rely on. It also adds a throw; site to every await in the iterator, which costs a second first-chance exception per failure. If you want the debugger to stop breaking, use one of the four options above, which are documented.
Gotchas
- ValueTask-based code is affected the same way. Async iterators are driven through
ValueTask<bool>andIValueTaskSource<bool>; the break does not depend onTaskvsValueTask, only on who catches. If you want the background, see what ValueTask is and when it is worth it. - It is not specific to
IAsyncEnumerable. Anyasync Taskmethod of yours awaited by framework code that catches (middleware,Parallel.ForEachAsync, a hosted service loop) triggers the same break. Iterators just make it common, because the idiomatic way to consume them is a framework LINQ operator. - Same with
Task.WhenAllwrappers. If the exception you finally catch is not the one that was thrown, read how to unwrap AggregateException from Task.WhenAll before changing debugger settings. async voidis a different problem. An exception from anasync voidmethod really is unhandled, it goes to the synchronization context and can crash the process. See async void vs async Task.- Inspecting the exception once stopped. The
$exceptionpseudovariable and the Exception Helper work at this break too; the tricks are in how to see the exception type at a breakpoint in Visual Studio.
Related
- What IAsyncEnumerable is and when you should use it
- How to see the exception type at a breakpoint inside a catch block in Visual Studio
- async void vs async Task in C#
- What is ValueTask and when is it worth it
Sources
- Break for Async User-Unhandled exceptions in the Visual Studio Debugger (Visual Studio blog, September 10, 2024)
- Manage exceptions with the debugger in Visual Studio (MS Learn)
- Debug only user code with Just My Code (MS Learn)
DebuggerDisableUserUnhandledExceptionsAttributeandDebugger.BreakForUserUnhandledException(API reference)- dotnet/runtime#103105, the API proposal for the attribute and method
- Exceptions in IAsyncEnumerable not passed upwards properly (Stack Overflow)
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.