Microsoft MVP성태의 닷넷 이야기
.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상 [링크 복사], [링크+제목 복사],
조회: 22446
글쓴 사람
정성태 (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)
13693정성태7/24/20247244개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/20248025디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/20247385디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/20247019오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/20248516디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/20247630닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/20248060닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/20247855오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/20248002스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/20248180닷넷: 2279. C# - 문자열 보간식 사례 (예: 조건 연산자 사용)
13683정성태7/18/20247651오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
13682정성태7/18/20247869닷넷: 2278. WPF - 스레드에 종속되는 DependencyObject파일 다운로드1
13681정성태7/17/20247471닷넷: 2277. C# 13 - (2) 메서드 그룹의 자연 타입 개선 (메서드 추론 개선)파일 다운로드1
13680정성태7/16/20247850닷넷: 2276. C# - Method Group, Natural Type, function_type파일 다운로드1
13679정성태7/16/20246934Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
13678정성태7/15/20247065VS.NET IDE: 191. Visual Studio 2022 - .NET 5 프로젝트를 Docker Support로 실행했을 때 오류
13677정성태7/15/20247148오류 유형: 916. MSBuild - CheckEolTargetFramework (warning NETSDK1138)
13676정성태7/14/20247326Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/20249117C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법 [1]파일 다운로드1
13674정성태7/13/20248000오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20248442닷넷: 2275. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
13672정성태7/10/20247152닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
13671정성태7/10/20247261오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20247381오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20247395개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20246621닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...