Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2006. C# - GC.KeepAlive 메서드의 역할 [링크 복사], [링크+제목 복사],
조회: 15250
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 4개 있습니다.)
.NET Framework: 435. .NET GC - 하위 세대의 객체를 포함하는 상위 세대의 참조를 추적하기 위한 card-table
; https://www.sysnet.pe.kr/2/0/1670

.NET Framework: 458. 닷넷 GC가 순환 참조를 해제할 수 있을까요?
; https://www.sysnet.pe.kr/2/0/1740

.NET Framework: 2005. C# - 생성한 참조 개체가 언제 GC의 정리 대상이 될까요?
; https://www.sysnet.pe.kr/2/0/13052

.NET Framework: 2006. C# - GC.KeepAlive 메서드의 역할
; https://www.sysnet.pe.kr/2/0/13053




C# - GC.KeepAlive 메서드의 역할

지난 글에서,

C# - 생성한 참조 개체가 언제 GC의 정리 대상이 될까요?
; https://www.sysnet.pe.kr/2/0/13052

GC의 정리 대상이 되는 시점을 살펴봤는데요, 사실 일반적으로는, 위와 같은 JIT/GC 최적화가 문제 될 것이 없습니다. 그런데, 이게 문제가 될 수 있는 특별한 상황이 다음의 예제 코드에 있습니다.

C# and GC.KeepAlive()
; https://manski.net/2013/08/c-and-gc-keepalive/

해당 코드를 보면,

class SomeClass
{
  // This field is initialized somewhere 
  // in the constructor (not shown here).
  public SomeOtherClass Value;
 
  ...

  ~SomeClass()
  {
     // "Value" can't be used anymore 
     // after Dispose() has been called.
     this.Value.Dispose();
  }
}
 
...
 
void MyMethod()
{
  SomeClass obj = new SomeClass();
  SomeOtherClass valueObj = obj.Value; // 이 코드 이후로는 obj 개체를 참조하지 않음!

  // ... 만약, 바로 이 시점에 GC가 호출된다면?

  SomeOtherMethod(valueObj);
  YetAnotherMethod();
  // obj still alive here? Possibly not.
}

JIT 컴파일러는 MyMethod 수행 시, obj 개체를 "valueObj = obj.Value" 이후부터 사용하지 않는다는 것을 알게 되고 그래서 GC 대상으로 지정을 합니다. 그런 와중에, 하필 SomeOtherMethod 메서드가 호출되기 전에 obj 개체가 GC 수집된다면 어떻게 될까요? 게다가 obj 타입에서 정의한 "~SomeClass" 종료자까지 호출이 된다면, 결국 "this.Value.Dispose()" 메서드까지 호출될 것이고, 그럼 SomeOtherMethod 수행 시점에는 obj.Value의 내부 상태는 불안정한 상태일 것이고, 따라서 SomeOtherMethod 수행 시 다양한 예외가 발생할 수 있습니다.

결국, 위와 같은 특별한 상황에서는 "obj" 개체가 해제되지 않도록 어떤 식으로든 개체를 "사용"하는 코드를 넣어야 합니다. 가령 별 의미는 없겠지만 하다못해 ToString()이라도 호출해야 하는 것입니다.

SomeClass obj = new SomeClass();
SomeOtherMethod(obj.Value);
obj.ToString(); // 이 시점까지 obj에 대한 GC 해제를 막기 위해!

바로 이런 경우를 위한 전용 메서드로, 닷넷은 GC.KeepAlive라는 메서드를 제공하는데요, 따라서 obj.ToString()과 같은 식의 호출 대신 다음과 같이 처리할 수 있습니다.

SomeClass obj = new SomeClass();
SomeOtherMethod(obj.Value);
GC.KeepAlive(obj); // GC 해제를 막기 위해

여기서 재미있는 것은, GC.KeepAlive의 구현 코드가 비어 있다는 점입니다.

// https://referencesource.microsoft.com/#mscorlib/system/gc.cs,310
[MethodImpl(MethodImplOptions.NoInlining)]
public static void KeepAlive(object obj)
{
}

왜냐하면, 이것은 순전히 JIT 컴파일러로 하여금 해당 개체가 KeepAlive를 호출하는 지점까지는 살아 있어야 한다는 "신호"를 주는 목적만 달성하면 되기 때문입니다.

참고로, "C# and GC.KeepAlive()" 글에서는 JIT 컴파일러의 이러한 개체 수명에 대한 최적화를 "lookahead optimization"이라는 용어를 사용하는데, 일단은 Google 검색으로는 닷넷 측에서의 문서에서는 해당 용어로 검색되는 것이 없습니다.




아울러, 다음의 글도 함께 보시면 좋겠죠. ^^

When do I need to use GC.KeepAlive?
; https://devblogs.microsoft.com/oldnewthing/20100813-00/?p=13153

위의 글에서도 finalizer로 인한 문제 사례를 들고 있는데요, 그래서 저런 복잡한 문제들로 인해 "Raymond Chen"은 다음과 같은 결론을 내고 있습니다.

If I ruled the world, I would decree that the only thing you can do in a finalizer is perform some tests to ensure that all the associated external resources have already been explicitly released, and if not, raise a fatal exception: System.Exception.Resource­Leak.


종료자(Finalizer)에서는 다른 의미 있는 작업은 하지 말고, 오직 자원 해제가 잘 되었는지에 대한 테스트와 그로 인한 ResourceLeak을 알리는 예외 발생만 해야 한다고!




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







[최초 등록일: ]
[최종 수정일: 10/5/2022]

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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...
NoWriterDateCnt.TitleFile(s)
12437정성태12/1/202017972VS.NET IDE: 155. pfx의 암호 키 파일을 Visual Studio 없이 등록하는 방법
12436정성태12/1/202018135오류 유형: 687. .NET Core 2.2 빌드 - error MSB4018: The "RazorTagHelper" task failed unexpectedly.
12435정성태12/1/202025216Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 [1]파일 다운로드1
12434정성태11/30/202019056Windows: 180. C# - dynamicport 값의 범위를 알아내는 방법
12433정성태11/29/202017773Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY파일 다운로드1
12432정성태11/29/202019272Windows: 178. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR [1]파일 다운로드1
12431정성태11/27/202016116.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/202018536오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/202018620디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/202016750VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202017619.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/202016006오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/202017653VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202017963VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202018594.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202016014.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202015302.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202015242오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202016116VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202018366오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202016088오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202017169오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202017413.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019538VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018517.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020676.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...