How can I use DebugBreak() in C#?
Asked Answered
Z

5

32

What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.

Zoes answered 19/9, 2008 at 18:18 Comment(0)
E
46

I also like to check to see if the debugger is attached - if you call Debugger.Break when there is no debugger, it will prompt the user if they want to attach one. Depending on the behavior you want, you may want to call Debugger.Break() only if (or if not) one is already attached

using System.Diagnostics;

//.... in the method:

if( Debugger.IsAttached) //or if(!Debugger.IsAttached)
{
  Debugger.Break();
}
Elastin answered 19/9, 2008 at 21:1 Comment(0)
B
25

Put the following where you need it:

System.Diagnostics.Debugger.Break();
Brought answered 19/9, 2008 at 18:20 Comment(0)
D
8

https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.break#System_Diagnostics_Debugger_Break

#if DEBUG
  System.Diagnostics.Debugger.Break();
#endif
Diu answered 19/9, 2008 at 18:20 Comment(1)
Great +1 for #if DEBUG! It's awfully when dev. leaves this code in release.Draw
L
3

You can use System.Diagnostics.Debugger.Break() to break in a specific place. This can help in situations like debugging a service.

Lovering answered 19/9, 2008 at 18:20 Comment(0)
C
3

The answers from @Philip Rieck and @John are subtly different.

John's ...

#if DEBUG
  System.Diagnostics.Debugger.Break();
#endif

only works if you compiled with the DEBUG conditional compilation symbol set.

Phillip's answer ...

if( Debugger.IsAttached) //or if(!Debugger.IsAttached)
{
  Debugger.Break();
}

will work for any debugger so you will give any hackers a bit of a fright too.

Also take note of SecurityException it can throw so don't let that code out into the wild.

Another reason no to ...

If no debugger is attached, users are asked if they want to attach a debugger. If users say yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit.

from https://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx

Clinandrium answered 21/3, 2016 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.