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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
14027정성태10/15/2025489닷넷: 2371. C# - CRC64 (System.IO.Hashing의 약식 버전)파일 다운로드1
14026정성태10/15/2025520닷넷: 2370. 닷넷 지원 정보의 "package-provided" 의미
14025정성태10/14/2025793Linux: 126. eBPF (bpf2go) - tcp_sendmsg 예제
14024정성태10/14/2025829오류 유형: 984. Whisper.net - System.Exception: 'Cannot dispose while processing, please use DisposeAsync instead.'
14023정성태10/12/20251251닷넷: 2369. C# / Whisper 모델 - 동영상의 음성을 인식해 자동으로 SRT 자막 파일을 생성 [1]파일 다운로드1
14022정성태10/10/20252118닷넷: 2368. C# / NAudio - (AI 학습을 위해) 무음 구간을 반영한 오디오 파일 분할파일 다운로드1
14021정성태10/6/20252666닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [1]파일 다운로드1
14020정성태10/2/20252302Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례
14019정성태10/1/20252435Linux: 124. eBPF - __sk_buff / sk_buff 구조체
14018정성태9/30/20251799닷넷: 2366. C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법파일 다운로드1
14017정성태9/29/20252262Linux: 123. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
14016정성태9/28/20252540Linux: 122. eBPF - __attribute__((preserve_access_index)) 사용법
14015정성태9/22/20251982닷넷: 2365. C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제파일 다운로드1
14014정성태9/17/20251968닷넷: 2364. C# - stun.l.google.com을 사용해 공용 IP 주소와 포트를 알아내는 방법파일 다운로드1
14013정성태9/14/20252611닷넷: 2363. C# - Whisper.NET Library를 이용해 음성을 텍스트로 변환 및 번역하는 예제파일 다운로드1
14012정성태9/9/20252862닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20253502닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20253316오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20253777닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20254354닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20254762닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20255053Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20254029오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20254614오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20254879닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...