Breakpoint that breaks when data changes in a managed language - c#

I have a class with a list property that seems to lose an element under certain circumstances. I cannot find out when this happens.
So what I'd like to do is set up a Visual Studio breakpoint that will pause the program the moment this value changes. A conditional breakpoint would not work in this scenario, since I have no idea what is removing this breakpoint.
To put it another way, I want my program to stop the moment myList.Count evaluates to a new number.
Any ideas on how to do this?

This is not possible in C# or any of the other .NET languages due to CLR limitations. The Visual Studio native code debugger supports data breakpoints (link) for C++ code which do exactly this but this is not supported for managed code. You could try to break on or intercept Add and Remove method calls on the collection as suggested in the other answer to this question.

What about swapping out List<T> for ObservableCollection<T> and listen for the CollectionChanged event? It implements the IList<T> interface so there should be enough overlap in available methods to result in syntax and semantic compatibility.

This is now possible in Visual Studio 2019.
See release notes here: https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes
This article goes into some detail using Preview 2.
https://devblogs.microsoft.com/visualstudio/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/
Note that this is for .NET Core only and not the soon-to-be-legacy full fledged Windows only .NET framework.

I'm assuming Visual Studio is IDE.
Set a breakpoint, right click it, select condition, type myList.Count, and choose Has Changed.

Subclass List<t> with your own class, then override Count (or Add/Remove) and add a breakpoint in the method you create.
EDIT: As mentioned in comments, this would require a great deal of effort since the Add and Remove methods aren't virtual; a complete rewrite of the methods would be needed.
Also, subclassing Collection<t> would apparently be a better solution (though I can't discern a reason why since Add/Remove aren't virtual members for Collection<t> either; comments?).

You can set data breakpoints in visual studio but this is going to be difficult to do for managed code, as the garbage collector may move the object around. That said, you may still be able to pull it off. You will have to enable native debugging for your process. Load SOS in the immediate window and use !DumpObject to find the address of the backing store for the Count property. Using this address, create a new data breakpoint with this address and then continue and trigger the issue.

Find all usages for this particular property and add breakpoint to all lines that removes elements from this list.
Or you may create your own IList implementation and set breakpoint to Remove method (you can't subclass List without changing all you clients, because List::Remove isn't virtual).

This is maybe more of a question than an answer, but you can step into Framework code when debugging, provided you set up your Visual studio that way. It could be that you can then put the breakpoint into the actual List implementation.

this may sound too out of the way or complex but can you use timer/background thread to keep testing the count value and do a Debugger.Break() whenever it finds the value different from its previous instance.

Related

Break when any member of an class (or object) called

I am currently debugging my application. (.Net Framework 4.6.2)
I have an instance of a class, that is somehow getting modified when performing a specific function (on debugging). I would now like to understand, what accessed and changed the object.
void PerformCalculationWithObject(MyClass obj)
{
DoSomething(obj); // calls a lot of different operations
// which sometimes modify obj, and sometimes not.
}
But the class is large and complex, and many function are called underneath the function.
I am aware that my biggest issue is the lack of good object-design in this legacy code, which leads to this problem.
So the question is, if there is a possibility to auto-break, when some member of the class (maybe even just fron specific instance) is called (without putting plenty of break-points).
If you're using VS 2019 and .NET Core 3.0 there are data breakpoints that can be set on an object from the watch window. Just right click on an expression in the watch window (in this case add a watch for obj) and then choose "Break when value changes".
More info on this is over at: https://devblogs.microsoft.com/visualstudio/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/
I appreciate this might not help you as you're debugging a legacy application but perhaps either it can run .NET Core 3 while debugging or some other user will find this answer useful.
Something I usually do in such cases is change the class member varibles which I suspect to change to properties with a get and set method and then put a breakpoint int the set method.

Can VS Debugger break on change of an Object ID? Similar to C++ [duplicate]

How can I track a variable's values as they change, at runtime, in C#? I'm interested in the same functionality that the debugger provides when I'm tracing a variable through execution steps, only that I need to call upon it from my code. Some sort of key-value observing, but for all kinds of variables(local, class, static, etc), not only properties. So, basically, receive a notification when a variable's value changes.
You are working from the assumption that the debugger can track variable changes. It can't.
It is possible with unmanaged code, the processor has dedicated debug registers that allow setting data breakpoints. Up to three are provided. It generates a hardware interrupt when it sees a particular memory location getting written. This otherwise very useful feature isn't available in managed code however. The garbage collector is completely incompatible with it, it moves objects around, giving them another address.
The managed debugger does support a "when hit" condition on a breakpoint, allowing you to dump info to the output window. That however requires a breakpoint, it cannot be triggered by a change in variable value. It also really slows down code execution since the debugger actually enters a break state before executing the condition.
The obvious place to put such a breakpoint is in a property setter. Which is what you'll need to implement this feature in code. You can do anything you want in that setter, using the Trace class for example.
To add to what Marc said, if you want to do this for lots of properties and methods you might want to check out aspect oriented programming techniques, and libraries such as PostSharp.
http://www.sharpcrafters.com/postsharp
The managed debugger uses the ICorDebug COM API for pretty much everything. The part that you're interested is ICorDebugValue and its descendants. Note that a LOT of the debugging API requires that the process be not running (ie, have encountered a breakpoint) in order for the various inspections to happen. A high level overview of ICorDebug is here. The documentation on it is kinda sparse, but some Googling may help. Good luck.
The only sensible way you could do that without the debugger would be: don't use a variable, but use a property, and (perhaps conditionally) add trace to the setter:
private int myValue;
public int MyValue {
get {return myValue;}
set {
SomeTraceMethod(myValue, value, ...);
myValue = value;
}
}
Obviously this cannot then be used for arbitrary fields/variables.
As others mentioned a mechanism like that makes only sense when using properties. In .NET you can then make use of the INotifyPropertyChanged interface.
For a sample how to implement it see
How to: Implement the INotifyPropertyChanged Interface
The referenced article talks explicitly about Windows Forms, but you are not bound to that (the interface is actually declared in the System.ComponentModel namespace in System.dll). In fact, this interface is widely used for data binding scenarios, e.g. in WPF.

Track an instance in C#? [duplicate]

This question already has answers here:
When debugging, is there a way to tell if an object is a different instance?
(3 answers)
Closed 7 years ago.
Is there a way to track a single instace in C#/.NET in Visual Studio while debugging? I find it would be really useful sometimes.
Another way to look at it would be breakpoints on instances rather than code. Therefore, every time my instance is accessed and/or modified the execution stops and I am presented with the line of code which accesses/modifies my instance.
In C++ the equivalence would be monitoring the piece of memory where the instance is located, or simply a pointer to the instance. This approach doesn't work with managed code as the objects in .NET are moved around, therefore I need an equivalence for pointers in C++.
I am aware of WeakReferences in C# but I am not sure if they are of any use while debugging?
Edit1:
This question is different from "When debugging, is there a way to tell if an object is a different instance? " as I am not interested in comparing two references, but I want to access a single object.
There's nothing that I'm aware of out of the box, but VS does support conditional breakpoints. One option would be to:
Place breakpoints on all of the methods on your class that you're interested in
Debug your code through until the first of these is hit
Find the HashCode of the instance
Make all of the breakpoints coditional on GetHashCode() == the hash code you previously retrieved
Let the application run on until the breakpoint is hit again
Look in the Call Stack window to see which line of code is calling your method
A little clunky, but will work...
Add a watch, like this:
https://msdn.microsoft.com/en-us/library/0taedcee.aspx
TLDNR: highlight the variable or expression you want to watch, then right-click and choose "Add to Watch" from the context menu. The variable will then be in the "Watch" window for you to observe.
As you step through your code, the expression should turn red when the value changes.

Monitoring changes of a private field in an external assembly without source

I want to monitor (or place a breakpoint on) each change of a static field which is member of an internal class which resides in an external assembly for which I don't have code:
Assembly: PresentationCore.dll
Class : MS.Internal.MemoryPressure
Field : private static long _totalMemory
Ideally I should be able to see the stacktraces which trigger the changes.
Is this possible with VS and if yes then how do I have to setup VS in order to do this? Or will I need some external profiling tool?
You cannot set a breakpoint on a field. You are in luck, there's only one method that modifies the value, called AddToTotal. Debug + New Breakpoint + Break At Function. Type "MS.Internal.MemoryPressure.AddToTotal" and untick the "Use IntelliSense" option. The debugger will break as soon as the method is called, typically when the code creates a bitmap. You will only have machine code to look at.
As soon as it breaks, you can add a watch for MS.Internal.MemoryPressure._totalMemory. Adjust the breakpoint in the disassembly so it breaks past the field assignment.
Since PresentationCore is part of .Net you can debug the framework source
Take a look at this question
what about this:
http://ayende.com/blog/4106/nhibernate-inotifypropertychanged
Both RedGate Reflector as well as JetBrains Resharper can help you do it. They both decompile the assembly and generate the C# source code after which they allow you to work with it as if it were yours including placing breakpoints, watching the stack, etc.
I started with reflector, but now (starting from v.6) I switched to resharper it seems at this point to be more robust. Resharper has a 30 days trial, reflector used to be free I am not sure what it is now

Tool for finding ways to get an object instance inside the debugger?

Right now I'm looking at a bug in some C# code where I need to get a given object instance at some location. I'm sitting on a breakpoint at that location in the debugger and can jump back up the stack and view the object instance that I need to get. I suspect that there is a way to get that instance from what I have (foo.bar.baz.bla.bla.bla or something like that) but I'm not knowledgeable enough about the code to know how to find it.
Hypothetical Example:
I'm sitting in the debugger at line 2485 in some one eases code and realize that the program needs to, right here, set the FooBat property on the enclosing WizBang object (the one that the function 27 steps up the call stack was called on) but I don't have any direct references to the enclosing WizBang object. However I suspect that one of the other object I do have access to has access to something that has access to something that does have access to the enclosing WizBang object. But that gives me about 10K things to look through and, oh by the way, I can also access 42 different WizBang objects that are not the one I want so I also need to check that it really is the same object as the one 27 steps up the stack. If I can just find how to get access to it I can add SomeExp.FooBat = true; right here on line 2485 and close this bug!
My question is: has anyone made a tool that uses reflection and bruit force to search chains of properties and members to find one that will give a desired object instance?
Yes I know this is an O(bd) problem and often won't work but it's computer time, not programmer time and when it does work, it would be fantastic!
p.s. I give it less than even odd of what I want existing (now <g/>).
maybe you should try the "Immediate window" where you can enter c# live. It can evaluate only expressions and assignments (no declarations etc).
You can find the immediate window from Debug->Windows->Immediate (Ctrl-Alt-I by default)
Did you try that already?
Maybe you can use the watch-window of the visual-studio debugger. You could insert your instance once and watch it every step.
Although reading all your comments and posts I'm not sure whether I correctly understood what you want. Did you try conditional breakpoints in Visual Studio? They may help as well. You can use them to check whether your object fulfills some conditions and just stop in that case.
I think what you're after is something that you would have to write yourself. That said, I don't imagine it to be very difficult - after all, you just need to write a method that uses reflection to traverse whatever object structure you're working with, checking for a specific condition. Then, you simply set a breakpoint (or hit Pause) and then run your method on whatever object structure you need. You can probably set the method to [Conditional(DEBUG)] so it doesn't appear in the release version of your program.

Categories

Resources