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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  [114]  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11108정성태11/13/201622013.NET Framework: 624. WPF - Line 요소를 Canvas에 위치시켰을 때 흐림(blur) 현상파일 다운로드1
11107정성태11/9/201626295오류 유형: 371. Post cache substitution is not compatible with modules in the IIS integrated pipeline that modify the response buffers.파일 다운로드1
11106정성태11/8/201626558.NET Framework: 623. C# - PeerFinder를 이용한 Wi-Fi Direct 데이터 통신 예제 [2]파일 다운로드1
11105정성태11/8/201621077.NET Framework: 622. PeerFinder Wi-Fi Direct 통신 시 Read/Write/Dispose 문제
11104정성태11/8/201619943개발 환경 구성: 305. PeerFinder로 Wi-Fi Direct 연결 시 방화벽 문제
11103정성태11/8/201620425오류 유형: 370. PeerFinder.ConnectAsync의 결과 값인 Task.Result를 호출할 때 System.AggregateException 예외 발생
11102정성태11/8/201620496오류 유형: 369. PeerFinder.FindAllPeersAsync 호출 시 System.UnauthorizedAccessException 예외 발생
11101정성태11/8/201622694.NET Framework: 621. 닷넷 프로파일러의 오류 코드 - 0x80131363
11100정성태11/7/201630313개발 환경 구성: 304. Wi-Fi Direct 지원 여부 확인 방법 [1]
11099정성태11/7/201632184.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201621469오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201624457오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201627925디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201624598.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201626258VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201626105웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201633239.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201627059VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201628614VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201628365디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201631545.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625891.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201620186오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201635037.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201622872오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201629168Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
... 106  107  108  109  110  111  112  113  [114]  115  116  117  118  119  120  ...