Reputation: 14558
I'm looking for a way to detect how code is called during a debugging session in Visual Studio. Trying to differentiate these two contexts:
(I'm doing this because I have some non-release thread validation code I want to disable in the second case.)
Anyone have a way to do this, or ideas about things to pursue? I'm fine with hacky, tricksy methods, even if they are specific to a particular version of VS.
Things that don't work:
Upvotes: 4
Views: 2206
Reputation: 100029
This situation typically arises when methods that Visual Studio assumes are pure (i.e. evaluation has no impact on the state of the program) either have side effects or have preconditions that the debugger violates.
These situations are best solved using the following tools:
DebuggerBrowsableAttribute: Apply this attribute to properties:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
get
method is not pure, i.e. the getter alters the state of the program, either through setting a cached value or otherwiseget
method has preconditions the debugger could violate, such as threading restrictions, cross-thread invocations (don't forget implicit if you use COM interop)DebuggerDisplayAttribute: Apply this attribute to all types whose ToString()
implementation performs non-trivial operations (avoid debugger performance impact) or has preconditions the debugger might not meet (e.g. threading requirements). This attribute is used instead of calling ToString()
for these types.
DebuggerTypeProxyAttribute: Apply this attribute to types that require special consideration for when, what, and how information is presented in the debugger. The .NET framework itself uses this attribute extensively to provide features like clear output for the List<T>
and HashMap<T>
types, and even to improve information available for types like Lazy<T>
that are sometimes OK to evaluate and other times could affect the state of the program.
Upvotes: 2
Reputation: 10488
As far as ordinary debugging goes, I think this is what you want:
System.Diagnostics.Debugger.IsAttached
Here's the documentation.
This won't help with the watch window though. On this, maybe the StackTrace
class can help but I haven't tried it myself. It's in the same namespace.
Upvotes: 1