developer tip

.NET 용 Visual Studio 디버거 팁 및 요령

optionbox 2020. 11. 2. 07:52
반응형

.NET 용 Visual Studio 디버거 팁 및 요령


VS의 디버거로 수년 동안 작업 해 왔지만 가끔씩 전에는 알아 차리지 못했던 기능을 발견하고 "젠장! 어떻게 놓쳤을 까? 너무 유용 해!"라고 생각 합니다.

[면책 조항 :이 팁은 C # 프로젝트의 VS 2005에서 작동하며, VS 또는 기타 언어의 이전 버전에 대한 보장은 없습니다.]

개체 인스턴스 추적

주어진 클래스의 여러 인스턴스로 작업합니까? 어떻게 구분할 수 있습니까? 가비지 수집 전 프로그래밍 시대에는 참조를 추적하기가 쉬웠습니다. 메모리 주소 만 확인하면됩니다. .NET에서는 그렇게 할 수 없습니다. 개체가 움직일 수 있습니다. 다행히 시계보기를 사용하면 시계를 마우스 오른쪽 버튼으로 클릭하고 '객체 ID 만들기'를 선택할 수 있습니다.

시계보기 http://img403.imageshack.us/img403/461/52518188cq3.jpg

그러면 인스턴스 값 뒤에 {1 #}, {2 #} 등이 추가되어 인스턴스에 고유 한 라벨을 효과적으로 부여합니다. 다음과 같이 보입니다.

번호가 매겨진 인스턴스 http://img383.imageshack.us/img383/7351/11732685bl8.jpg

레이블은 해당 개체의 수명 동안 유지됩니다.

감시 된 변수의 의미있는 값

기본적으로 감시 변수의 값은 유형입니다. 필드를 보려면 필드를 확장해야합니다. 필드가 많거나 복잡한 작업을 수행하는 경우 시간이 오래 걸릴 수 있습니다 (또는 시간 초과!).

그러나 일부 사전 정의 된 유형은 더 의미있는 정보를 표시합니다.

  • 문자열은 실제 내용을 표시합니다.
  • 목록과 사전은 요소 개수 등을 보여줍니다.

의미있는 정보 http://img205.imageshack.us/img205/4808/37220487md1.jpg

내 유형에 맞게 사용하는 것이 좋지 않을까요?

흠 ...

... NET Reflector를 사용한 좋은 시간 DebuggerDisplay은 내 사용자 지정 유형 속성을 사용하여 얼마나 쉽게 수행 할 수 있는지 보여줍니다 .

[System.Diagnostics.DebuggerDisplay("Employee: '{Name}'")]
public class Employee {
    public string Name { get { ... } }
    ...
}

... 다시 실행하고 ...

따다! http://img60.imageshack.us/img60/926/79816018ha1.jpg

여기에 주제에 대한 더 많은 정보가 있습니다. MSDN

모든 예외에서 중단

... 코드로 처리되는 것들까지! 나는 내가 태어난 이래로 이것에 대해 알지 못하는 것에 대해 그런 n00b이지만 어쨌든 여기에 있습니다-아마도 이것은 언젠가 누군가를 도울 것입니다.

예외가 발생할 때마다 디버깅 된 프로세스를 강제로 디버그 모드로 전환 할 수 있습니다. 몇 시간 동안 버그를 찾아서 이런 코드를 발견 한 적이 있습니까?

try {
    runStrangeContraption();
} catch(Exception ex) {
    /* TODO: Will handle this error later */
}

이러한 경우 모든 예외를 포착하는 것은 정말 편리합니다. 디버그> 예외 ... (Ctrl-Alt-E) 에서 활성화 할 수 있습니다 . 필요한 각 예외 유형에 대해 'Thrown'열의 상자를 선택합니다.


저에게는 이마를 두드리는 몇 가지 순간이었습니다. 당신은 당신의 것을 공유 하시겠습니까?


두 가지 인 코드 트릭 :

System.Diagnostics.DebuggerStepThrough 속성이 정말 마음에 듭니다 . 디버깅 할 때 기본적으로 VS가 코드를 입력하지 않도록 클래스, 메서드 또는 속성에 연결할 수 있습니다. DebuggerHidden 속성 보다 더 선호합니다. 그래도 디버그가 필요한 경우 무시 된 코드에 중단 점을 넣을 수 있기 때문입니다.

또 다른 (때때로) 유용한 호출은 System.Diagnostics.Debugger.Launch ()입니다 . 실행에 도달하면 "디버거 선택"대화 상자가 표시되고 디버거가 시작됩니다. 약간 무례하지만 다른 프로세스에 의해 생성되어 즉시 코드를 실행하는 프로세스와 같이 프로세스에 연결하는 것이 특히 불쾌 할 때 유용합니다.


try {
    // do something big
}
catch {
    // breakpoint set here:
    throw CantHappenException("something horrible happened that should never happen.");
}

원래 던져진 예외를 어떻게 볼 수 있습니까? 감시 창에 $ exception을 입력합니다.


내가 배운 또 다른 깔끔한 트릭은 다음과 같습니다.

System.Diagnostics.Debugger.Break()

프로그래밍 방식으로 디버거가 다음 명령어에서 중단되도록합니다. 정말 좋은 부분이 또한 컴파일 된 프로그램에 대한 작품이다 릴리스 정보를 디버깅하지 않고, 모드.


I always make sure to set the "Name" property on new threads that I create. That way, when I'm debugging I can more easily identify different threads.


Of course, check out the VS tip of the day:

http://blogs.msdn.com/SaraFord/


A few from me

  • Uncheck the "Enable Just My Code" option in Tools->Options->Debugging.
  • Conditional breakpoints - they save my life almost every day
  • Use the .NET framework source if things get ugly

.load sos in the Immediate window :)


Tools -> Attach To Process - easy to forget, but with it I can debug script in web pages, managed code loaded up in another process (think an add-in model), or even unmanaged code. Be careful with letting it automatically pick the type of debugging you're interested in.

Tracepoints (and other breakpoint features... right click on the breakpoint and have fun)! - http://blogs.msdn.com/saraford/archive/2008/06/13/did-you-know-you-can-use-tracepoints-to-log-printf-or-console-writeline-info-without-editing-your-code-237.aspx

The immediate window is awesome.

Remote Debugging is very useful if you deploy apps (and can get to the machine where the problem can be reproduced).

There are tons more. Try getting into WinDbg and SoS!


I found the Modules window useful a lot of times. It tells whether the debugger has loaded a required dll and which version of the dll is loaded. It also lets you manually load or unload a dll.


Conditional breaks are very useful if you have code that is repeated a lot but only fails under a specific set of conditions, such as code in a loop, methods called from a loop, or methods called from multiple threads. Put the break statement at the line of interest and set its conditions to match the error case. (There is a quick example here.)


Two from me: one that I hope everyone uses all over the place:

Debug.Assert(<condition>, <message>)

the second DebuggerHidden:

<DebuggerHidden()> _
Public Sub ReadDocumentProperty(ByVal propertyName As String, ByRef PropVal As Integer, ByVal DefaultVal As Integer)
    Try
        Dim prop As Office.DocumentProperty
        prop = CustomProps.Item(propertyName)
        PropVal = CType(prop.Value, Integer)
    Catch
        PropVal = DefaultVal
    End Try
End Sub

Even if you have Debug, Exceptions, Break on thrown exceptions set, exceptions in here will not be caught.


Create a Macro for attaching to a process and assign to an unused keyboard shortcut. Much faster than going: debug -> attach to process -> search for the process in the processes list ->...


How about setting the IDE to break into exceptions when they occur, even when we don't have any debug point set.

Debug--> Exceptions-->Commmon Language Runtime Exceptions-->Thrown

This makes finding hidden exception handling problems a breeze. Actually this is kind of a setting every developer should have set through out the development, to avoid any unhanded or even handled exceptions that are going underneath.


In unmanaged code you can set "data breakpoints". They user the debug registers of the CPU to issue an INT3 and the debugger stops on that instruction with no overhead during run time (in older version the debugger stepped through the program checking the memory..... slow!)

This is useful if you have some corruption at a knwon address (stack / heap vaiable getting clobbered).

Also AutoExp.dat in ide\packages\debugger can be customized to show your data structures.

pointer, mb shows a hex dump in the watch window http://msdn.microsoft.com/en-us/magazine/dd252945.aspx

Yum!

참고URL : https://stackoverflow.com/questions/201450/visual-studio-debugger-tips-tricks-for-net

반응형