성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - GC.KeepAlive 메서드의 역할</h1> <p> 지난 글에서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - 생성한 참조 개체가 언제 GC의 정리 대상이 될까요? ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13052'>https://www.sysnet.pe.kr/2/0/13052</a> </pre> <br /> GC의 정리 대상이 되는 시점을 살펴봤는데요, 사실 일반적으로는, 위와 같은 JIT/GC 최적화가 문제 될 것이 없습니다. 그런데, 이게 문제가 될 수 있는 특별한 상황이 다음의 예제 코드에 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# and GC.KeepAlive() ; <a target='tab' href='https://manski.net/2013/08/c-and-gc-keepalive/'>https://manski.net/2013/08/c-and-gc-keepalive/</a> </pre> <br /> 해당 코드를 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > class SomeClass { // This field is initialized somewhere // in the constructor (not shown here). public SomeOtherClass Value; ... <span style='color: blue; font-weight: bold'>~SomeClass()</span> { // "Value" can't be used anymore // after Dispose() has been called. <span style='color: blue; font-weight: bold'>this.Value.Dispose();</span> } } ... void MyMethod() { SomeClass obj = new SomeClass(); SomeOtherClass valueObj = obj.Value; // 이 코드 이후로는 obj 개체를 참조하지 않음! // ... 만약, 바로 이 시점에 GC가 호출된다면? <span style='color: blue; font-weight: bold'>SomeOtherMethod(valueObj);</span> YetAnotherMethod(); // obj still alive here? Possibly not. } </pre> <br /> JIT 컴파일러는 MyMethod 수행 시, obj 개체를 "valueObj = obj.Value" 이후부터 사용하지 않는다는 것을 알게 되고 그래서 GC 대상으로 지정을 합니다. 그런 와중에, 하필 SomeOtherMethod 메서드가 호출되기 전에 obj 개체가 GC 수집된다면 어떻게 될까요? 게다가 obj 타입에서 정의한 "~SomeClass" 종료자까지 호출이 된다면, 결국 "this.Value.Dispose()" 메서드까지 호출될 것이고, 그럼 SomeOtherMethod 수행 시점에는 obj.Value의 내부 상태는 불안정한 상태일 것이고, 따라서 SomeOtherMethod 수행 시 다양한 예외가 발생할 수 있습니다.<br /> <br /> 결국, 위와 같은 특별한 상황에서는 "obj" 개체가 해제되지 않도록 어떤 식으로든 개체를 "사용"하는 코드를 넣어야 합니다. 가령 별 의미는 없겠지만 하다못해 ToString()이라도 호출해야 하는 것입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > SomeClass obj = new SomeClass(); SomeOtherMethod(obj.Value); <span style='color: blue; font-weight: bold'>obj.ToString();</span> // 이 시점까지 obj에 대한 GC 해제를 막기 위해! </pre> <br /> 바로 이런 경우를 위한 전용 메서드로, 닷넷은 GC.KeepAlive라는 메서드를 제공하는데요, 따라서 obj.ToString()과 같은 식의 호출 대신 다음과 같이 처리할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > SomeClass obj = new SomeClass(); SomeOtherMethod(obj.Value); <span style='color: blue; font-weight: bold'>GC.KeepAlive(obj);</span> // GC 해제를 막기 위해 </pre> <br /> 여기서 재미있는 것은, GC.KeepAlive의 구현 코드가 비어 있다는 점입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // <a target='tab' href='https://referencesource.microsoft.com/#mscorlib/system/gc.cs,310'>https://referencesource.microsoft.com/#mscorlib/system/gc.cs,310</a> [MethodImpl(MethodImplOptions.NoInlining)] public static void KeepAlive(object obj) { } </pre> <br /> 왜냐하면, 이것은 순전히 JIT 컴파일러로 하여금 해당 개체가 KeepAlive를 호출하는 지점까지는 살아 있어야 한다는 "신호"를 주는 목적만 달성하면 되기 때문입니다.<br /> <br /> 참고로, "<a target='tab' href='https://manski.net/2013/08/c-and-gc-keepalive/'>C# and GC.KeepAlive()</a>" 글에서는 JIT 컴파일러의 이러한 개체 수명에 대한 최적화를 "lookahead optimization"이라는 용어를 사용하는데, 일단은 Google 검색으로는 닷넷 측에서의 문서에서는 해당 용어로 검색되는 것이 없습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 아울러, 다음의 글도 함께 보시면 좋겠죠. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > When do I need to use GC.KeepAlive? ; <a target='tab' href='https://devblogs.microsoft.com/oldnewthing/20100813-00/?p=13153'>https://devblogs.microsoft.com/oldnewthing/20100813-00/?p=13153</a> </pre> <br /> 위의 글에서도 <a target='tab' href='https://www.sysnet.pe.kr/2/0/347'>finalizer</a>로 인한 문제 사례를 들고 있는데요, 그래서 저런 복잡한 문제들로 인해 "Raymond Chen"은 다음과 같은 결론을 내고 있습니다.<br /> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> 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.ResourceLeak.<br /> </div><br /> <br /> 종료자(Finalizer)에서는 다른 의미 있는 작업은 하지 말고, 오직 자원 해제가 잘 되었는지에 대한 테스트와 그로 인한 ResourceLeak을 알리는 예외 발생만 해야 한다고!<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
7722
(왼쪽의 숫자를 입력해야 합니다.)