Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2006. C# - GC.KeepAlive 메서드의 역할 [링크 복사], [링크+제목 복사],
조회: 15237
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12412정성태11/16/202020662.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017440오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017586디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019428.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034676도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019775.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020763.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018630.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019253.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018162.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019666.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202018917VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015135오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018662.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018180오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018199.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015221VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202018001오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015623오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015287오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019829.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019479디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202018637.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202017676오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202018463.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202019207Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...