Microsoft MVP성태의 닷넷 이야기
.NET Framework: 458. 닷넷 GC가 순환 참조를 해제할 수 있을까요? [링크 복사], [링크+제목 복사],
조회: 32364
글쓴 사람
정성태 (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




닷넷 GC가 순환 참조를 해제할 수 있을까요?

아래와 같은 질문이 있군요. ^^

c# 상호참조 질문 
; http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_QnA_etc&page=1&page_num=35&select_arrange=last_comment&desc=desc&sn=off&ss=on&sc=on&keyword=&no=3167&category=

질문의 내용은, 닷넷 GC가 순환 참조를 해제할 수 있느냐입니다. 사실, 이 문제는 WeakReference를 이용해 간단하게 테스트 해볼 수 있습니다. ^^

using System;

namespace circular_ref
{
    class Program
    {
        static void Main(string[] args)
        {
            WeakReference wrA = null;
            WeakReference wrB = null;

            CallCrossRef(ref wrA, ref wrB);

            Console.WriteLine((wrA.Target as RefA)._a);
            Console.WriteLine((wrB.Target as RefB)._b);
        }

        private static void CallCrossRef(ref WeakReference wrA, ref WeakReference wrB)
        {
            RefA a = new RefA();
            RefB b = new RefB();

            wrA = new WeakReference(a);
            wrB = new WeakReference(b);

            a._instanceB = b;
            a._a = 5;
            b._instanceA = a;
            b._b = 6;
        }
    }

    public class RefA
    {
        public RefB _instanceB;
        public int _a;
    }

    public class RefB
    {
        public RefA _instanceA;
        public int _b;
    }
}

서로 순환 참조하고 있고 위의 결과를 실행하면 5와 6값이 화면에 출력됩니다.

하지만, 다음과 같이 GC.Collect를 한번 해주면,

static void Main(string[] args)
{
    WeakReference wrA = null;
    WeakReference wrB = null;

    CallCrossRef(ref wrA, ref wrB);

    GC.Collect();

    Console.WriteLine((wrA.Target as RefA)._a);
    Console.WriteLine((wrB.Target as RefB)._b);
}

GC가 동작하고 순환참조임에도 불구하고 정상적으로 RefA a, RefB b 인스턴스가 해제된 것을 확인할 수 있습니다.

GC의 동작과 관련해서는 card-table 개념과 함께 소개해 드렸던 링크에서,

.NET GC - 하위 세대의 객체를 포함하는 상위 세대의 참조를 추적하기 위한 card-table
; https://www.sysnet.pe.kr/2/0/1670

마이크로소프트 측 직원이 아주 자세하게 설명해 주고 있으니 참고하시는 것도 좋겠습니다. ^^

  1. Memory allocation, a walk down the history
  2. Why use garbage collection
  3. Reference Counting Garbage Collection
  4. Mark-sweep garbage collection
  5. Copying garbage collection
  6. Optimizing reference counting garbage collection
  7. Handling overflow in mark stage
  8. Generational Garbage Collection
  9. How does the GC find object references




추가적으로! 참조로 인한 메모리 릭이 발생할 수 있는 전형적인 사례가 하나 있는데 바로 "이벤트"입니다. 테스트를 위해 다음과 같이 코드를 만들어 보면,

using System;

namespace circular_ref
{
    class Program
    {
        static void Main(string[] args)
        {
            CallEventFire();
            GC.Collect();

            Console.ReadLine();
        }

        private static void CallEventFire()
        {
            EventPublisher publisher = new EventPublisher();
            EventSubscriber subscriber = new EventSubscriber();
            publisher.Fire += subscriber.DoFire;
        }
    }

    public class EventPublisher
    {
        public delegate void FireEvent();
        public event FireEvent Fire;

        protected void OnFire()
        {
            if (Fire != null)
            {
                Fire();
            }
        }

        ~EventPublisher()
        {
            Console.WriteLine("~EventPublisher.Called()");
        }
    }

    public class EventSubscriber
    {
        public void DoFire()
        {
        }

        ~EventSubscriber()
        {
            Console.WriteLine("~EventSubscriber.Called()");
        }
    }
}

GC.Collect 이후 정상적으로 2개의 소멸자가 모두 호출되는 것을 볼 수 있습니다. 그런데 이 상태에서 "EventPublisher publisher = new EventPublisher();"의 코드를 static으로 빼면 어떻게 될까요?

static EventPublisher publisher = new EventPublisher();

private static void CallEventFire()
{
 // EventPublisher publisher = new EventPublisher();
    EventSubscriber subscriber = new EventSubscriber();
    publisher.Fire += subscriber.DoFire;
}

얼핏 보면, publisher 인스턴스는 static 루트 객체가 있으니 소멸되지 않겠지만 subscriber 인스턴스는 범위를 벗어났으니 힙에서 제거되어야 합니다.

하지만, 아무런 소멸자도 호출되지 않습니다. 왜냐하면 이벤트 구독 자체가 대상 객체를 참조하기 때문입니다. 이런 일이 발생하는 흔한 경우가 바로 이벤트 구독이 남발하는 윈도우 폼 응용 프로그램입니다. Form 위에서 동적으로 컨트롤을 생성/삭제하는 경우 그 컨트롤에 이벤트 핸들러를 걸어 두면 객체가 힙에 쌓이게 됩니다. (다행히, 대부분의 윈도우 폼 응용 프로그램은 사용자가 필요 없을 때 종료시키기 때문에 메모리 릭 문제에서 비교적 자유롭습니다.)

물론, 해결 방법은 그냥 필요 없어졌을 때 이벤트 구독을 해제하면 됩니다. 위의 예제에서는 다음과 같이 추가해 주면 됩니다.

private static void CallEventFire()
{
    // EventPublisher publisher = new EventPublisher();
    EventSubscriber subscriber = new EventSubscriber();
    publisher.Fire += subscriber.DoFire;
    publisher.Fire -= subscriber.DoFire;
}

이렇게 하고 나서 다시 실행해 보면, GC.Collect 호출에서 "~EventSubscriber.Called()" 출력을 볼 수 있습니다.

(첨부 파일은 위의 예제 코드를 포함합니다.)




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







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

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

비밀번호

댓글 작성자
 



2014-08-25 11시50분
[ryujh] 안녕하세요. 이벤트 설명에서 의문점 있습니다.
publisher.Fire += subscriber.DoFire; 이렇게 명시적으로 했으니 publisher.Fire -= subscriber.DoFire; 하면 되겠지만
publisher.Fire += subscriber.DoFire; publisher.Fire += subscriber.DoFire; 이렇게 두번 이상했을 때(이러면 안되지만) publisher.Fire -= subscriber.DoFire; 이것을 두번 이상하려고 publisher.Fire 에 몇개 핸들러가 등록되었는지 찾아보려고 해도 알 수 없습니다. 처음부터 이런 문제 없도록 코드를 잘 작성할 수 밖에 없는지요?
[guest]
2014-08-26 12시33분
아래와 같은 방법이 있긴 하지만,

이벤트에 속한 이벤트 핸들러 확인
; http://www.sysnet.pe.kr/2/0/618

WPF 이벤트에 속한 핸들러 확인
; http://www.sysnet.pe.kr/2/0/624

너무 복잡한 경우에는 위와 같은 방법으로 세고 나서 해제하는 것도 상관없지만, 일반적으로는 저렇게 하는 것이 더 복잡할 수 있기 때문에 그냥 횟수를 관리하는 편이 좋을 것입니다. (현실적으로 봤을 때 중복하는 경우는 사실 많지 않지요.)

만약 중구난방으로 이벤트 구독/해제가 발생할 수 있는 상황이라면, WPF Prism 같은 프레임워크에서처럼 이벤트 publisher/subscriber 구조의 프레임워크를 사용하는 것도 한 방법일 것입니다.
정성태

... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12664정성태6/9/202115304오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
12663정성태6/9/202117692.NET Framework: 1065. Windows Forms - 속성 창의 디자인 설정 지원: 문자열 목록 내에서 항목을 선택하는 TypeConverter 제작파일 다운로드1
12662정성태6/8/202115415.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법파일 다운로드1
12661정성태6/4/202127421.NET Framework: 1063. C# - MQTT를 이용한 클라이언트/서버(Broker) 통신 예제 [4]파일 다운로드1
12660정성태6/3/202118142.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법 [1]파일 다운로드1
12659정성태6/2/202119035Linux: 40. 우분투 설치 후 MBR 디스크 드라이브 여유 공간이 인식되지 않은 경우 - Logical Volume Management
12658정성태6/2/202116820Windows: 194. Microsoft Store에 있는 구글의 공식 Youtube App
12657정성태6/2/202117626Windows: 193. 윈도우 패키지 관리자 - winget 설치
12656정성태6/1/202115942.NET Framework: 1061. 서버 유형의 COM+에 적용할 수 없는 Server GC
12655정성태6/1/202114594오류 유형: 722. windbg/sos - savemodule - Fail to read memory
12654정성태5/31/202115260오류 유형: 721. Hyper-V - Saved 상태의 VM을 시작 시 오류 발생
12653정성태5/31/202118507.NET Framework: 1060. 닷넷 GC에 새롭게 구현되는 DPAD(Dynamic Promotion And Demotion for GC)
12652정성태5/31/202115973VS.NET IDE: 164. Visual Studio - Web Deploy로 Publish 시 암호창이 매번 뜨는 문제
12651정성태5/31/202116179오류 유형: 720. PostgreSQL - ERROR: 22P02: malformed array literal: "..."
12650정성태5/17/202115509기타: 82. OpenTabletDriver의 버튼에 더블 클릭을 매핑 및 게임에서의 지원 방법
12649정성태5/16/202117702.NET Framework: 1059. 세대 별 GC(Garbage Collection) 방식에서 Card table의 사용 의미 [1]
12648정성태5/16/202116468사물인터넷: 66. PC -> FTDI -> NodeMCU v1 ESP8266 기기를 UART 핀을 연결해 직렬 통신하는 방법파일 다운로드1
12647정성태5/15/202116723.NET Framework: 1058. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용파일 다운로드1
12646정성태5/15/202115527사물인터넷: 65. C# - Arduino IDE의 Serial Monitor 기능 구현파일 다운로드1
12645정성태5/14/202115580사물인터넷: 64. NodeMCU v1 ESP8266 - LittleFS를 이용한 와이파이 접속 정보 업데이트파일 다운로드1
12644정성태5/14/202116852오류 유형: 719. 윈도우 - 제어판의 "프로그램 및 기능" / "Windows 기능 켜기/끄기" 오류 0x800736B3
12643정성태5/14/202116815오류 유형: 718. 서버 유형의 COM+ 사용 시 0x80080005(Server execution failed) 오류 발생
12642정성태5/14/202118513오류 유형: 717. The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
12641정성태5/13/202117317디버깅 기술: 179. 윈도우용 .NET Core 3 이상에서 Windbg의 sos 사용법
12640정성태5/13/202120912오류 유형: 716. RDP 연결 - Because of a protocol error (code: 0x112f), the remote session will be disconnected. [1]
12639정성태5/12/202117319오류 유형: 715. Arduino: Open Serial Monitor - The module '...\detection.node' was compiled against a different Node.js version using NODE_MODULE_VERSION
... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...