I have a large project that executes without problem when not debugging (even when running the debug build).
If I try to debug the project, when execution hits a certain MS CCR dependent library the debugger pauses execution:
The call stack at this point appears as follows:
This occurs even when "Debug"->"Exceptions..."->"CLR Exceptions" thrown and user-unhandled are both unchecked.
The problem appears to be happening in Microsoft.Core.Ccr.dll at Microsoft.Ccr.Core.TaskExecutionWorker.ExecuteTaskHelper(Microsoft.Ccr.Core.ITask currentTask) + 0x94 bytes since I upgraded the project to .net4.5 and added the latest version of Microsoft.Ccr.Core (4.0.261.0).
This is a major inconvenience to my debugging efforts as hitting these non-existent breakpoints means that other time-related parts of my project are almost impossible to debug correctly.
What could possibly be causing this behaviour and are there any options I've missed that might allow VS to ignore the problem?
After a dotPeek decompilation of TaskExecutionWorker.ExecuteTaskHelper I see the following:
if (!CausalityThreadContext.IsEmpty(threadCausalities) &&
CausalityThreadContext.RequiresDebugBreak(threadCausalities))
Debugger.Break();
I can see why they did this (I have unhandled exceptions somewhere) but now they've been gobbled by CCR, and the info I can see in the debugger makes this code-defined breakpoint somewhat pointless.
EDIT
It seems that I had added Causalities with property BreakOnReceive = true to the Dispatcher. As such this is expected behaviour. I can't see any possible use for this setting as the exceptions have been gobbled. Surely a better decision here would be to throw an exception rather than break the debugger. Hmmm...
Related
I have a large, complex C# GUI application which is crashing in a completely reproducible way, but I cannot easily diagnose the cause of the crash because rather than breaking the debugger with a call stack in the usual way, the debugging session completely exits.
The only hint is that there's a message at the end of the output window: STATUS_STACK_BUFFER_OVERRUN.
I am painstakingly trying to put breakpoints in at random places before the crash happens, trying to gradually get my breakpoints closer to where the problem happens, but this approach is not getting me anywhere quickly.
I'm wondering if there are any existing tools which work sort of like an instrumenting profiler, basically observing and logging all of the function enters and exits, so that when the program crashes with a corrupted stack, it's still possible to examine this external data to determine where execution was last happening?
I don't expect that this is a feature that most performance-oriented profilers have, since they are more concerned with how many times a function was called and for how long, but perhaps there's a tool which will tell me exactly what the last known running piece of code was?
I'm open to other suggestions if there's a way to solve/diagnose this within Visual Studio or using other techniques.
You can use a conditional breakpoint to trigger when the stack depth exceeds a certain value:
(new StackTrace()).GetFrames().Length > 60
The trick here is knowing where to put the breakpoint, as it has to be set somewhere in the recursive cycle. But if you know what triggers the error you might have enough intuition to choose some strategic places to put the check. You can also use a process of elimination: if the breakpoint isn't triggered, you know that code is not involved in the cycle.
Also note that the conditional breakpoint is costly and will significantly slow down the application being debugged. If you're not opposed to littering your code with debugging statements, you can call Debugger.Break() instead of setting breakpoints:
if (Debugger.IsAttached && (new StackTrace()).GetFrames().Length > 60)
Debugger.Break();
STATUS_STACK_BUFFER_OVERRUN means that someone blew passed the end or beginning of their stack variables, most likely in unmanaged or interop code.
If you attach the debugger in native mode or mixed mode, go to the Exceptions window and add a Win32 exception with the code 0xc0000409 (stack overflow). If you trigger the error, it should break in the debugger.
You can use my Runtime Flow tool to log all function calls in your application. After a crash you can see what was the last function enter.
So, I have found a lot of resources and StackOverflow questions on this exact topic, but it seems to only apply to pretty old versions of Visual Studi0 -- like 2012.
My issue is that I want the Debugger to ONLY break when an exception is UN-HANDLED. The official MSDN says that the Debugger breaks on what is called a "first-chance" exception, meaning that it is intended functionality to break even if the exception is going to be handled.
I find it incredibly annoying to have the Debugger break on an InvalidCastException that I have wrapped inside a try-catch. Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled? A common answer is to just disable breaking on that particular CLR Exception type, but that's honestly a ridiculous solution. I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
I can imagine your frustration, but there has to be something odd with your VisualStudio settings. I can assure you that on my setups, VS never catches exceptions that are handled, and that is/was true across all VS versions ranging from VS2008 upto VS2015.
"FirstChance exception" line you see in the output window is an information that an exception has been just thrown, at exactly that moment, before any handlers were triggered or stacks unwound.
But that does not imply any breaking in VisualStudio. Only a one-liner is written to the debug output, and program continues - stack is unwound, and nearest matching catch is executed, and program runs forward.
Now, the VS/Debugger/CLR can break on exceptions being throw, but it has to be turned on. You can get there by Debug->Windows->Exceptions, or press CTRL+D+E. When you click that, a new panel should appear, with a list of exceptions and one or two options for each of them:
break when thrown
break on unhandled
but that may vary depending on your VS version. For example, in VS Community 2015, there's only "Break when thrown", and "unhandled" is not visible, but still is active for all of them. You just can't turn off breaking on "unhandled".
Anyways, the important thing is that by default, all "unhandled" are selected, and none or almost none of "when thrown" is. In VS2015Community, I see following "when thrown" set by default:
some C++ "Platform::xxxx" exceptions
System.Reflection.MissingMetadata [<-C#]
System.Reflection.MissingRuntimeArtifact [<-C#]
System.Windows.Markup.XamlParseException [<-C#]
Javascript exception: Access Denied, code 0x80070005
some ManagedDebuggingAssistants: LoaderLock, ContextSwitch, ...
a few Win32 exceptions
and that's all. Maybe total of 10..20 very specific types, I didn't count. In "Common Language Runtime" group only three are checked by default, those listed above. No InvalidCastExceptions.
If your VS is triggering at the moment it is thrown, then it means that you, or someone that had access to your VS, has configured it differently. Most probably, in that "ExceptionSettings" panel, you have "InvalidCastException" marked as "break when thrown". Go there, see the state of the checkbox at "InvalidCastExceptions" and uncheck it, and retry.
If this helps for the case of InvalidCastExceptions, and if this problem happens for some other exceptions as well, then you can repeat it for any other type that you dont want to break-on-thrown. And yes, it means that at some point of time you (or someone else) have clicked there and checked them to break on them.
If you have many of them checked to break-on-thrown, then instead of clicking on each one, you can click on the subtree root and check/uncheck whole groups. (btw. maybe you had accidentaly clicked and checked a whole group a week or month ago?)
Also, there's a very useful "Restore Defaults" underrightclick and even a button called "Restore the list to default settings", both of which simply reset everything to the default settings (like in the list I wrote above: some C++, some reflection, some win32, and so on).
Finally, whatever exceptions you deselect for break-on-thrown in ExceptionSettings panel, VisualStudio will still break on any unhandled exceptions. (unless you see there another set of checkboxes, labelled as "unhandled" - there was such thing in i.e. VS2010Pro, but in VS2015Community I dont see it.. maybe it's a Pro thing)
As of Visual Studio 2015, you can go to Debug -> Windows -> Exception Settings. You define which exceptions to automatically break for on a case-by-case basis. There is also a link to this window when VS breaks for an exception - click on "Exception Settings" at the bottom of the window.
On my home computer, I only see one column, "Thrown", so to your point, there is no way to throw only unhandled exception. At work, though, I have a second column called "User Unhandled", which allows me to do exactly what you're talking about. Leaving "user unhandled" checked and unchecking "thrown" causes it to break only on unhandled exceptions, not on ones that are caught. I think this may be a feature of Visual Studio Professional edition - at home I use Community Edition.
If you use the higher VS version like the VS2015, it has no the option to enable/disable the Unhandled Exception like the Old VS version, but it has his own feature:
So if we just want to capture the unhandled exception, we could disable the checkbox.
Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled?
I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
But if you still want to get the first change exception messages that will be handled, it has no good workaround for this issue, since at this point the debugger does not know if the exception will be caught (handled) by the application, and if you enable the checkbox, it will capture the first-chance exception(When an exception is first thrown in the application, this is classified as a “first chance” exception).
Reference:
https://blogs.msdn.microsoft.com/visualstudioalm/2015/02/23/the-new-exception-settings-window-in-visual-studio-2015/
https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/understanding-exceptions-while-debugging-with-visual-studio/#unhandled.
Remember that you can define your own build configuration next to Release or Debug which can follow the #if <name> and #endif marks in your code. There you can for example decide if you want to focus on exception or not depending on configuration.
I have a client/server app. The server component runs, uses WCF in a 'remoting' fashion (binary formatter, session objects).
If I start the server component and launch the client, the first task the server does completes in <0.5sec.
If I start the server component with VS debugger attached, and then launch the client, the task takes upwards of 20sec to complete.
There are no code changes - no conditional compilation changes. The same occurs whether I have the server component compiled and running in 32-bit, 64-bit, with the VS hosting process, without the VS hosting process, or any combination of those things.
Possibly important: If I use the VS.NET profiler (sampling mode), then the app runs as quick as if there were no debugger attached. So I can't diagnose it that way. Just checked, instrumentation mode also runs quickly. Same for the concurrency profiling mode, works quickly.
Key data:
The app uses fairly heavy multithreading (40 threads in the standard thread pool). Creating the threads happens quickly regardless and is not a slow point. There are many locks, WaitHandles and Monitor patterns
The app raises no exceptions at all.
The app creates no console output.
The app is entirely managed code.
The app does map a few files on disk to a MemoryMappedFile: 1x750MB and 12x8MB and a few smaller ones
Measured performance:
CPU use is minimal in both cases; when debugger is attached, CPU sits at <1%
Memory use is minimal in both cases; maybe 50 or 60MB in both cases
There are plenty of page faults happening (ref MMF), however they happen more slowly when the debugger is attached
If the VS hosting process is not used, or basically the 'remote debugging monitor' comes into play, then that uses a decent amount CPU and creates a good number of page faults. But that's not the only time the problem is occurring
The performance difference is seen regardless of how the client is run. The only variable being changed is the server component being run via 'Start with debugging' vs launched from Explorer.
My ideas:
WCF slow when debugged?
MemoryMappedFiles slow when debugged?
40 threads used - slow to debug? Perhaps Monitors/locks notify debugger? Thread scheduling becomes strange/context switches very infrequent?
Cosmic background radiation granting intelligence and cruel sense of humour to VS
All seem stupidly unlikely.
So, my questions:
Why is this happening?
If #1 unknown, how can I diagnose / find out?
Since this is one of the first results when googling for this issue I would like to add my problem solution here in the hopes of saving someone 2 hours of research like in my case.
My code slowed down from 30 seconds without debugger attached to 4 minutes with debugger. because I forgot to remove a conditional breakpoint. These seem to slow down execution tremendously, so watch out for those
Exceptions can notably impact the performance of an application. There are two types of exceptions: 1st chance exceptions (the one gracefully handled with a try/catch block), and unhandled exceptions (that will eventually crash the application).
By default, the debugger does not show 1st chance exceptions, it just shows unhandled exceptions. And by default, it also shows only exceptions occurring in your code. However, even if it does not show them, it still handles them, so its performance may be impacted (especially in load tests, or big loop runs).
To enable 1st chance exceptions display in Visual Studio, click on "Debug | Exceptions" to invoke the Exceptions dialog, and check "Thrown" on the "Common language runtime" section (you can be more specific and choose wich 1st chance exception you want to see).
To enable 1st chance exceptions display originating from anywhere in the application, not just from your code, click on "Tools | Options | Debugging | General" and disable the "Enable Just My Code" option.
And for these specific "forensics mode" cases, I also strongly recommend to enable .NET Framework Source Stepping (it requires "Enable Just My Code" to be disabled). It's very useful to understand what's going on, sometimes just looking at the call stack is very inspiring - and helpful especially in the case of cosmic radiation mixup :-)
Two related interesting articles:
How to debug crashes and hangs
Configuring Visual Studio to Debug .NET Framework Source Code
Possible causes:
Various special kinds of breakpoints such as:
Conditional breakpoints
Memory changed breakpoints
Function breakpoints
Having the "Enable native code debugging" option checked.
This option makes debug runs slow as molasses.
This option is not under Tools -> Options -> Debug, (that would make too much sense,) it is under Project -> Properties -> Debug
Excessive use of System.Diagnostics.Debug.Write().
My benchmarks show that 1000 invocations of Debug.WriteLine() take only 10 milliseconds when running without debugging, but a whole 500 milliseconds when debugging. Apparently the Visual Studio Debugger, when active, intercepts DotNet debug output, and does extremely time-consuming stuff with it. (Over decades of using Microsoft products, we have come to expect nothing less from Microsoft.)
Replacing Debug.WriteLine() with kernel32.dll -> PInvoke -> OutputDebugStringW() does not help, because when running a DotNet application, Visual Studio completely ignores kernel32 debug output and only displays DotNet debug output, which is a completely different thing. (And I suppose that anything else would, again, make too much sense.)
Excessive amount of exceptions being thrown and caught, as another answer suggests.
Throwing an exception under DotNet is a mind-bogglingly slow operation.
Collecting a stack trace under DotNet is an insanely slow operation.
I have some places in the C# application where potential Exception's are not catched, but there is a try-finally block to release resources before crashing in case of an Exception.
When I run the code in Visual Studio and an Exception occurs, it breaks at the corrsponding line, marks it yellow and describes the exception.
That's fine.
But after having noticed and read the exception, I want my application to fail savely (execute the finally blocks). This is exactly what would happen if I ran the code outside Visual Studio. However, when I hit F5 to continue, it gets stuck on that very line, marking it over and over again.
What can I do to tell Visual Studio I want the application to continue = fail?
What's happening is you're seeing the Exception Assistant feature of Visual Studio. Whenever there is an unhandled exception in user code it will display to inform the user of the problem.
Unfortunately in certain circumstances it can't be made to go away and you get the behavior you're describing. It's definitely very frustrating when that happens. The best way to work around it is to disable the exception assistant.
Tools -> Options
Debugging -> Generale
Uncheck "Enable the exception assistant"
Sometimes I find I need to hit F5 several times. I know that it will stop on every rethrow or try-block that the exception goes through, so it may be that it is repeating because the exception is happening in a library function and is filtered through several try statements before leaving the library function. VS, however, will just show that library call several times. I've never gotten truly stuck, though. Hitting F5 a few times will get it moving again.
Visual studio will continue on after breaking on exceptions if you do have a matching catch statement for the type of exception being thrown.
However, you can turn off the exception assistant completely for specific exceptions by going to the Debug > Exceptions menu and unchecking the exceptions you would like to ignore.
When I debug a C# program and I get an exception throwed (either thrown by code OR thrown by the framework), the IDE stops and get me to the corresponding line in my code.
Everything is fine for now.
I then press "F5" to continue. From this moment, it seams like I'm in an infinite loop. The IDE always get me back to the exception line. I have to Shift + F5 (stop debugging/terminate the program) to get out of his.
I talked with some co-workers here and they told me that this happens sometime to them too.
What's happening?
You probably have the option "Unwind the callstack on unhandled exceptions" checked in Visual Studio. When this option is on Visual Studio will unwind to right before the exception, so hitting F5 will keep ramming into the same exception.
If you uncheck the option Visual Studio will break at the exception, but hitting F5 will proceed past that line.
This option is under menu Tools → Options → Debugging → General.
Update: According to Microsoft, this option was removed from Visual Studio in VS2017, and maybe earlier.
This is because the exception is un-handled and Visual Studio can not move past that line without it being handled in some manner. Simply put, it is by design.
One thing that you can do is drag and drop the execution point (yellow line/arrow) to a previous point in your code and modify the in memory values (using the Visual Studio watch windows) so that they do not cause an exception. Then start stepping through the code again1.
It is a better idea though to stop execution and fix the problem that is causing the exception, or properly handle the exception if the throw is not desired.
1 This can have unintended consequences since you are essentially re-executing some code (not rewinding the execution).
When the IDE breaks on the offending line of code, it stops just before executing the line that generated the exception. If you continue, it will just execute that line again, and get the exception again.
If you want to move past the error to see what would have happened, had the error not occurred, you can drag the yellow-highlighted line (the line that will execute next) down to the next line of code after the offending one. Of course, depending on what the offending line failed to do, your program may now be in a state that causes other errors, in which case you haven't really helped yourself much, and probably should fix your code so that the exception either doesn't occur, or is handled properly.
Once you get an exception Visual Studio (or whatever IDE you might be using) will not let you go any further unless the exception is handled in your code.
This behaviour is by design.
Some said that is by design, but it was never been before. You were able to F5 again and the code would continue until the end or next exception catch.
It was an useful behavior that worked well, and as developers, I think we should not reach artificial barriers while we are debugging and investigating issues in an application.
That said, I found a workaround to this (sort of):
press Ctr+Shift+E (Exception settings)
uncheck the "Common Language Runtime Exceptions" box
press F10 to continue only the exception you are stuck
check "Common Language Runtime Exceptions" again, if you want the breaks to happen again
That seems dirty, too much work for a thing that is used to be simpler, but I guess that is what we have for today.
An uncaught exception will bring down your app. Instead of this, VS will just keep you at the uncaught exception, You will have to terminate or backwind your app.