Microsoft MVP성태의 닷넷 이야기
.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상 [링크 복사], [링크+제목 복사],
조회: 22633
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  127  128  129  130  131  [132]  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1755정성태9/22/201434280오류 유형: 241. Unity Web Player를 설치해도 여전히 설치하라는 화면이 나오는 경우 [4]
1754정성태9/22/201424639VC++: 80. 내 컴퓨터에서 C++ AMP 코드가 실행이 될까요? [1]
1753정성태9/22/201420610오류 유형: 240. Lync로 세미나 참여 시 소리만 들리지 않는 경우 [1]
1752정성태9/21/201441070Windows: 100. 윈도우 8 - RDP 연결을 이용해 VNC처럼 사용자 로그온 화면을 공유하는 방법 [5]
1751정성태9/20/201438942.NET Framework: 464. 프로세스 간 통신 시 소켓 필요 없이 간단하게 Pipe를 열어 통신하는 방법 [1]파일 다운로드1
1750정성태9/20/201423832.NET Framework: 463. PInvoke 호출을 이용한 비동기 파일 작업파일 다운로드1
1749정성태9/20/201423732.NET Framework: 462. 커널 객체를 위한 null DACL 생성 방법파일 다운로드1
1748정성태9/19/201425384개발 환경 구성: 238. [Synergy] 여러 컴퓨터에서 키보드, 마우스 공유
1747정성태9/19/201428463오류 유형: 239. psexec 실행 오류 - The system cannot find the file specified.
1746정성태9/18/201426104.NET Framework: 461. .NET EXE 파일을 닷넷 프레임워크 버전에 상관없이 실행할 수 있을까요? - 두 번째 이야기 [6]파일 다운로드1
1745정성태9/17/201423035개발 환경 구성: 237. 리눅스 Integration Services 버전 업그레이드 하는 방법 [1]
1744정성태9/17/201431061.NET Framework: 460. GetTickCount / GetTickCount64와 0x7FFE0000 주솟값 [4]파일 다운로드1
1743정성태9/16/201420985오류 유형: 238. 설치 오류 - Failed to get size of pseudo bundle
1742정성태8/27/201426970개발 환경 구성: 236. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 [2]
1741정성태8/26/201421334.NET Framework: 459. GetModuleHandleEx로 알아보는 .NET 메서드의 DLL 모듈 관계파일 다운로드1
1740정성태8/25/201432507.NET Framework: 458. 닷넷 GC가 순환 참조를 해제할 수 있을까요? [2]파일 다운로드1
1739정성태8/24/201426535.NET Framework: 457. 교착상태(Dead-lock) 해결 방법 - Lock Leveling [2]파일 다운로드1
1738정성태8/23/201422046.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스파일 다운로드1
1737정성태8/20/201419764VS.NET IDE: 93. Visual Studio 2013 동기화 문제
1736정성태8/19/201425575VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [2]파일 다운로드1
1735정성태8/19/201418195.NET Framework: 455. 닷넷 사용자 정의 예외 클래스의 최소 구현 코드 - 두 번째 이야기
1734정성태8/13/201419856오류 유형: 237. Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.
1733정성태8/13/201426362.NET Framework: 454. EmptyWorkingSet Win32 API를 사용하는 C# 예제파일 다운로드1
1732정성태8/13/201434475Windows: 99. INetCache 폴더가 다르게 보이는 이유
1731정성태8/11/201427081개발 환경 구성: 235. 점(.)으로 시작하는 파일명을 탐색기에서 만드는 방법
1730정성태8/11/201422165개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
... 121  122  123  124  125  126  127  128  129  130  131  [132]  133  134  135  ...