Search code examples
.netdebuggingvisual-studio-2015breakpointsmanaged

Detecting when VS debugger is stopped at a breakpoint?


In managed .NET debugging with Visual Studio 2017, is there any way to detect whether your code is being called by the debugger context, i.e. when stopped at a breakpoint?

I believe this is known as the func-eval context (more here), and it happens when you stop a breakpoint and the debugger automatically calls your code in order to display ToString() results (if enabled) on property values in the Locals, Autos, Watch, etc. windows, and also to evaluate arbitrary functions you enter while stopped.

Note that I'm aware of Debugger.IsAttached, but this is not the same; it indicates if the process is being debugged, regardless of whether the debugger is stopped or running at the time of the call. This question seeks a more specific case: Debugger.IsAttached must be true, but that's not enough because it doesn't say whether you're in the debugger's func-eval context.

Since this should be just a simple global bool value somewhere, I'm hoping the solution doesn't involve COM calls (i.e. to ICorDebugAppDomain).


Solution

  • No. The code can't tell if it's being invoked by a func-eval. In general, we don't really want code behaving differently under a debugger vs. normally... that leads to horribly hard problems to debug.

    If you're trying to avoid func-evals, you could use the DebuggerDisplay attribute. You could use Debugger.NotifyOfCrossThreadDependency() to signal the debugger to abort a func-eval. (see https://blogs.msdn.microsoft.com/eliofek/2012/12/12/why-do-we-get-the-function-evaluation-requires-all-threads-to-run/ for more details)