Microsoft MVP성태의 닷넷 이야기
.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상 [링크 복사], [링크+제목 복사],
조회: 22450
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

ElementHost 컨트롤의 메모리 누수 현상

아래와 같은 질문이 있습니다.

ElementHost Memory Leak 현상
; https://www.sysnet.pe.kr/3/0/4749

ElementHost Memory Leak 현상 (아래내용과 동일 첨부 추가^^)
; https://www.sysnet.pe.kr/3/0/4750


"ElementHost Memory Leak 현상 (아래내용과 동일 첨부 추가^^)" 글의 첨부 파일은 WPF 프로젝트와 WinForm 프로젝트를 포함하고 있는데, 소스 코드를 약간 바꿔 1초마다 다음과 같이 ElementHost를 지속적으로 사용/제거를 반복하게 만들어 보았습니다.

public partial class MainForm : Form
{
    Timer t = new Timer();

    public MainForm()
    {
        InitializeComponent();
        t.Interval = 1000;
        t.Tick += T_Tick;
        t.Start();
    }

    private void T_Tick(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            ElementHost addElementHost = new ElementHost() { Dock = DockStyle.Top };
            addElementHost.Child = new WPFUserControl();

            this.testPanel.Controls.Add(addElementHost);
        }

        this.testPanel.Controls.Clear();

        Process proc = Process.GetCurrentProcess();
        string mem = proc.PrivateMemorySize64.ToString();

        if (this.memoryLabel.InvokeRequired)
        {
            this.Invoke(new MethodInvoker(delegate { this.memoryLabel.Text = mem; }));
        }
        else
        {
            this.memoryLabel.Text = mem;
        }
    }
}

그래서 이 예제 프로젝트를 실행하면 1초마다 10개의 ElementHost가 생성/삭제를 반복하는데 메모리는 지속적으로 증가하는 것을 볼 수 있습니다. 한마디로 메모리 누수(memory leak) 현상이 발생하고 있는 것입니다.

이런 경우 가장 먼저 해볼 것이 ElementHost가 IDisposable을 구현하고 있는가... 하는 것입니다. 실제로 ElementHost는 Control을 상속받고 있으며 여기서 IDisposable을 상속받고 있습니다. 즉, 가능하면 Dispose를 호출해 주는 것이 권장되는 것입니다.

이럴 때 다음과 같이 예제 코드를 바꿔보면 메모리 누수 현상이 없어집니다.

List<ElementHost> list = new List<ElementHost>();

for (int i = 0; i < 10; i++)
{
    ElementHost addElementHost = new ElementHost() { Dock = DockStyle.Top };
    addElementHost.Child = new WPFUserControl();

    list.Add(addElementHost);
    this.testPanel.Controls.Add(addElementHost);
}

this.testPanel.Controls.Clear();

foreach (ElementHost elem in list)
{
    elem.Dispose();
}


그런데, 왜 이런 현상이 발생하는 것일까요? 원래 (Full) GC가 2번 이상 수행되면 Finalizer가 구현된 경우 Dispose가 불리게끔 되어 있습니다. 실제로 Control 객체가 상속받은 System.ComponentModel.Component의 Finalize 메서드는 내부적으로 다음과 같이 Dispose(false) 코드를 호출합니다.

~Component()
{
    this.Dispose(false);
}

Dispose 메서드에 false를 주었다는 것은 "Managed 자원"은 어차피 Finalizer가 호출되는 시점이면 GC에 의해 해제되었을 것이므로 "Unmanaged 자원을 해제"하라는 것입니다. 이에 대해서는 다음의 글을 참고하세요.

.NET IDisposable 처리 정리
; https://www.sysnet.pe.kr/2/0/347

그런데, ElementHost에 정의된 Dispose 메서드에는 false인 경우 해제하는 작업이 전혀 없습니다.

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        try
        {
            if (this._hostContainerInternal != null)
            {
                this._hostContainerInternal.Dispose();
                this._hostContainerInternal = null;
            }
        }
        finally
        {
            try
            {
                if (this._hwndSource != null)
                {
                    this.DisposeHWndSource();
                }
            }
            finally
            {
                InputManager.Current.PostProcessInput -= new ProcessInputEventHandler(this.InputManager_PostProcessInput);
                IDisposable child = this.Child as IDisposable;
                if (child != null)
                {
                    child.Dispose();
                }
            }
        }
    }
    base.Dispose(disposing);
}

그렇다면, ElementHost의 Dispose 작업 중에 처리되는 것들은 Unmanaged 자원과는 전혀 무관하다는 것인데요. 아무래도 이것은 개발자의 오판이 아닌가 싶습니다. 왜냐하면, 분명히 있기 때문에 저렇게 메모리 누수가 발생하는 것이므로!

게다가 재현 코드를 돌려 보면, dwm.exe 프로세스의 메모리도 함께 증가하면서 전체적인 UI 반응이 느려지는 것을 볼 수 있습니다. 즉, ElementHost로 인해 해제되지 않은 자원 중에 dwm.exe와도 관련있는 자원이 해제되지 않아서 발생하는 문제로 보입니다.

어쨌든, 그나마 다행인 것은 Dispose를 명시적으로 호출해 주면 메모리 누수가 없어지므로 사용하는 측에서 좀 조심해 주면 됩니다. ^^




호기심 삼아서, ElementHost.Dispose의 어떤 과정에서 leak을 유발했는지 좀 더 탐색해 보았습니다. 그 결과, 다음과 같이 2가지 코드만 수행해 주면 문제가 없었습니다.

Type type = elem.GetType();

// this.DisposeHWndSource();
MethodInfo miHwnd = type.GetMethod("DisposeHWndSource", BindingFlags.NonPublic | BindingFlags.Instance);
if (miHwnd == null)
{
    return;
}

miHwnd.Invoke(elem, null);

// InputManager.Current.PostProcessInput -= new ProcessInputEventHandler(this.InputManager_PostProcessInput);
MethodInfo mi = type.GetMethod("InputManager_PostProcessInput", BindingFlags.NonPublic | BindingFlags.Instance);
if (mi == null)
{
    return;
}

Type inputManager = InputManager.Current.GetType();
EventInfo ei = inputManager.GetEvent("PostProcessInput");

System.Delegate del = mi.CreateDelegate(typeof(System.Windows.Input.ProcessInputEventHandler), elem);

MethodInfo ei_mi = ei.GetRemoveMethod();
ei_mi.Invoke(InputManager.Current, new object[] { del });

즉, 다음의 2개 코드였습니다.

this.DisposeHWndSource();
InputManager.Current.PostProcessInput -= new ProcessInputEventHandler(this.InputManager_PostProcessInput);

InputManager.Current.PostProcessInput의 경우 전역 static 이벤트 핸들러를 제거하지 않아서 문제가 발생하는 것은 일면 이해가 됩니다. 전역 객체로부터의 이벤트를 제거하지 않아 지속적으로 객체가 해제되지 않는 현상은 이미 유명합니다.

아울러 DisposeHWndSource 코드에도 메모리 누수 코드가 있습니다.

private void DisposeHWndSource()
{
    ((IKeyboardInputSink) this._hwndSource).KeyboardInputSite = null;
    this._hwndSource.Dispose();
    this._hwndSource = null;
}

실제로 이 중에서 this._hwndSource.Dispose()만 Reflection을 이용해 호출해도 메모리 누수 현상이 사라집니다.

FieldInfo fieldInfo = type.GetField("_hwndSource", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

if (fieldInfo == null)
{
    return;
}

object objValue = fieldInfo.GetValue(elem);
Type hwndSourceType = objValue.GetType();
MethodInfo miDispose = hwndSourceType.GetMethod("Dispose", BindingFlags.Public | BindingFlags.Instance);
miDispose.Invoke(objValue, null);

HwndSource 타입은 IDisposable은 구현했지만 Finalizer는 구현하지 않은 객체입니다. 따라서, 해당 클래스에서 Unmanaged 자원을 사용하고 있는 코드가 있다면 (Dispose를 명시적으로 호출하지 않는 경우) GC에 의해 절대로 해제되지 않게 됩니다. 그리고, 테스트 결과는 그것이 있다는 것을 의미합니다. HwndSource.Dispose 메서드를 분석해서 구체적으로 어떤 것이 문제인지 확인해 보고 싶었으나... 코드가 너무 길어서 ^^ 이건 나중으로 미루겠습니다.




이 글의 결론은, ElementHost를 사용하지 않더라도 다음의 2가지 사항을 주의해야 한다는 것입니다.

  1. InputManager.Current로부터 이벤트 구독을 했다면 반드시 해제해 줄 것.
  2. HwndSource 객체를 생성했다면 반드시 명시적으로 Dispose 메서드를 호출해 줄 것.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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)
13667정성태7/7/20246621닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247700Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247878Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247472닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247490닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247413Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247520오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247858개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248235개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247911닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248074Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247846닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247787오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247937닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249245닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248487닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248410개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247957오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248278오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249343개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247758오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248197개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248868닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248306오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248198스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...