问题
I know I can use Debugger.IsAttached to detect whether a debugger is attached, but I want to be able to do something like
if (Debugger.IsAttached && Debugger.BreakpointIsSet && Debugger.BreakpointHitCount > 0)
timeout *= 100;
someEvent.WaitOne(timeout);
The reason is some of my testing scenarios involve activity on other threads. Viewing things under the debugger naturally disturbs this process. I'd like my main testing thread to block longer while I'm stepping after a breakpoint hit on some other thread, but not block as long if the debugger isn't attached, or it is but a breakpoint hasn't been hit yet.
Is something equivalent to the above possible; for example, using P/Invoke to an unmanaged debug API?
回答1:
I'm not sure I fully understand what it is you plan to achieve here - but it sounds like whatever solution might be cooked up, it will only expound on the certainty and confusion of what is really happening when your threads signal each other, which is confusing enough as is, especially when attaching a debugger.
I'd say you're better off staying away from the debugger on this one and doing good ol' "printf debugging", and of course looking at the ThreadID from which each message was generated.
That said, if you still wish to use a debugger for this, it might be useful to look at only one thread (and one thread only) while the others are all blocked, and monitor its activity when the system enters a corrupt state - this link might be helpful for that: http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/07/17/automatically-freezing-threads-brrrrr.aspx
回答2:
Break points are a function of the IDE (Visual Studio) and the debugger, not of the .NET framework itself... As far as I know the closest you can get to what you need is to use Visual Studio "Breakpoint Condition" feature...
回答3:
I am not aware of such a possibility, but what exactly is a breakpoint that has been hit? It is paused execution of at least the thread your breakpoint is hit in. Going on from this, you could maybe use Thread.ThreadState and check for the state Suspended. For this to work, you would need to have a reference to the thread that is of interest to you.
Disclaimer: I don't know, whether this will work or whether this has any side effects, so even if it works, use it only in debugging and make sure, it is not in your production code.
来源:https://stackoverflow.com/questions/5422018/how-can-i-detect-whether-a-debugger-is-attached-and-a-breakpoint-has-been-set