Microsoft MVP성태의 닷넷 이야기
.NET Framework: 741. windbg로 확인하는 객체의 GC 여부 [링크 복사], [링크+제목 복사]
조회: 12416
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

windbg로 확인하는 객체의 GC 여부

객체가 GC되었는지 어떻게 알 수 있을까요? 테스트를 위해 다음과 같이 간단하게 프로그램을 만들고,

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Instance();

            Console.ReadLine();    // .NET 4 + x86 + Release 모드로 실행 후,
                                   // 이 시점에 Dump를 뜨고,

            GC.Collect(2, GCCollectionMode.Forced);     // 엔터를 치면 GC가 수행되고,
                                                        // 이 시점에 다시 Dump를 뜸
            Console.ReadLine();
        }

        private static void Instance()
        {
            Program pg = new Program();
        }
    }
}

두 번의 덤프를 떠 보면 됩니다. 첫 번째 덤프는 Instance 메서드 내에서 생성한 pg 객체가 범위를 벗어났지만 아직 Garbage Collector가 실행된 적이 없으므로 GC Heap에 객체가 있을 것입니다. 반면 두 번째 덤프를 뜬 시기에는 강제로 GC.Collect를 호출했으므로 0세대 GC Heap에 있던 pg 객체가 없어졌을 것입니다.

실제로 그런지 덤프 파일을 windbg로 확인해 볼까요? ^^

첫 번째 덤프 파일을 열고, ConsoleApp2.Program 객체가 GC Heap에 있는지 다음과 같이 확인할 수 있습니다.

0:000> .loadby sos clr

0:000> !dumpheap -type ConsoleApp2.Program
 Address       MT     Size
04b4242c 02c34d34       12     

Statistics:
      MT    Count    TotalSize Class Name
02c34d34        1           12 ConsoleApp2.Program
Total 1 objects

이때의 GC heap을 구해 보면,

0:000> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x04b41018
generation 1 starts at 0x04b4100c
generation 2 starts at 0x04b41000
ephemeral segment allocation context: none
 segment     begin  allocated      size
04b40000  04b41000  04b45ff4  0x4ff4(20468)
Large object heap starts at 0x05b41000
 segment     begin  allocated      size
05b40000  05b41000  05b45508  0x4508(17672)
Total Size:              Size: 0x94fc (38140) bytes.
------------------------------
GC Heap Size:    Size: 0x94fc (38140) bytes.

0 세대 힙의 시작 위치가 0x04b41018이고, pg 객체의 메모리 주소가 04b4242c이므로 0 세대 힙에 위치한 것이 맞는다는 것을 알 수 있습니다.

그다음, GC.Collect 이후의 덤프로 "!dumpheap -type ConsoleApp2.Program" 명령을 내리면 예상했던 데로 객체가 없습니다.

0:000> !dumpheap -type ConsoleApp2.Program
 Address       MT     Size

Statistics:
      MT    Count    TotalSize Class Name
Total 0 objects

GC 힙의 상황을 보면,

0:000> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x04b44300
generation 1 starts at 0x04b4100c
generation 2 starts at 0x04b41000
ephemeral segment allocation context: none
 segment     begin  allocated      size
04b40000  04b41000  04b4430c  0x330c(13068)
Large object heap starts at 0x05b41000
 segment     begin  allocated      size
05b40000  05b41000  05b45508  0x4508(17672)
Total Size:              Size: 0x7814 (30740) bytes.
------------------------------
GC Heap Size:    Size: 0x7814 (30740) bytes.

pg 객체가 있던 04b4242c 주소를 넘어서 0 세대 힙의 시작 주소가 0x04b44300로 설정된 것을 볼 수 있습니다. 만약, GC되지 않았다면 (승격되었을 것이므로) 1 세대 힙의 시작 주소인 0x04b4100c와 0 세대 힙의 시작 주소 사이에 객체의 주소가 출력되었을 것입니다.




객체가 해제되었는지 덤프를 통해 확인하는 것은 사실 좀 번거로운 작업입니다. 다행히 이보다 더 쉬운 방법이 있는데 바로 WeakReference를 사용하는 것입니다. 이를 통해 예제 코드를 다음과 같이 바꿔서 windbg 없이도 해당 객체가 GC되었는지를 알 수 있습니다.

using System;

namespace ConsoleApp2
{
    class Program
    {
        static WeakReference _wr;

        static void Main(string[] args)
        {
            Instance();
            Console.WriteLine(_wr.IsAlive); // IsAlive == True
            Console.ReadLine();

            GC.Collect(2, GCCollectionMode.Forced);
            Console.WriteLine(_wr.IsAlive); // IsAlive == False
            Console.ReadLine();
        }

        private static void Instance()
        {
            Program pg = new Program();
            _wr = new WeakReference(pg);
        }
    }
}

간단하죠? ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/28/2018]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13304정성태3/31/20234387VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233729Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234357Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234452Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234093Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233870Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233826Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234486Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233823Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234113Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234282.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234343오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234460Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234830.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234326.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233513Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233626Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233789Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234231Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233821Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234044Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233582오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233914Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233839Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234588개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234116오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...