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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11467정성태3/19/201817453오류 유형: 455. Visual Studio Installer - 업데이트 실패
11466정성태3/18/201818050개발 환경 구성: 355. 한 대의 PC에서 2개 이상의 DirectX 게임을 실행하는 방법
11463정성태3/15/201820307.NET Framework: 733. 스레드 간의 read/write 시에도 lock이 필요 없는 경우파일 다운로드1
11462정성태3/14/201823912개발 환경 구성: 354. HTTPS 호출에 대한 TLS 설정 확인하는 방법 [1]
11461정성태3/13/201826289오류 유형: 454. 윈도우 업데이트 설치 오류 - 0x800705b4 [1]
11460정성태3/13/201818385디버깅 기술: 112. windbg - 닷넷 메모리 덤프에서 전역 객체의 내용을 조사하는 방법
11459정성태3/13/201819623오류 유형: 453. Debug Diagnostic Tool에서 mscordacwks.dll을 찾지 못하는 문제
11458정성태2/21/201820482오류 유형: 452. This share requires the obsolete SMB1 protocol, which is unsafe and could expose your system to attack. [1]
11457정성태2/17/201824648.NET Framework: 732. C# - Task.ContinueWith 설명 [1]파일 다운로드1
11456정성태2/17/201830746.NET Framework: 731. C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법 [7]파일 다운로드1
11455정성태2/17/201819963오류 유형: 451. ASP.NET Core - An error occurred during the compilation of a resource required to process this request.
11454정성태2/12/201828921기타: 71. 만료된 Office 제품 키를 변경하는 방법
11453정성태1/31/201820732오류 유형: 450. Azure Cloud Services(classic) 배포 시 "Certificate with thumbprint ... doesn't exist." 오류 발생
11452정성태1/31/201826114기타: 70. 재현 가능한 최소한의 예제 프로젝트란? [3]파일 다운로드1
11451정성태1/24/201819918디버깅 기술: 111. windbg - x86 메모리 덤프 분석 시 닷넷 메서드의 호출 인자 값 확인
11450정성태1/24/201836181Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법 [1]
11449정성태1/23/201822856오류 유형: 449. 단위 테스트 - Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.VideoRecorderEngine' or one of its dependencies. [1]
11448정성태1/20/201820953오류 유형: 448. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS0619 관련 오류 발생
11447정성태1/20/201822217.NET Framework: 730. dotnet user-secrets 명령어 [2]파일 다운로드1
11446정성태1/20/201822531.NET Framework: 729. windbg로 살펴보는 GC heap의 Segment 구조 [2]파일 다운로드1
11445정성태1/20/201820826.NET Framework: 728. windbg - 눈으로 확인하는 Workstation GC / Server GC
11444정성태1/19/201820373VS.NET IDE: 125. Visual Studio에서 Selenium WebDriver를 이용한 웹 브라우저 단위 테스트 구성파일 다운로드1
11443정성태1/18/201821820VC++: 124. libuv 모듈 살펴 보기
11442정성태1/18/201818855개발 환경 구성: 353. ASP.NET Core 프로젝트의 "Enable unmanaged code debugging" 옵션 켜는 방법
11441정성태1/18/201817300오류 유형: 447. ASP.NET Core 배포 오류 - Ensure that restore has run and that you have included '...' in the TargetFrameworks for your project.
11440정성태1/17/201820609.NET Framework: 727. ASP.NET의 HttpContext.Current 구현에 대응하는 ASP.NET Core의 IHttpContextAccessor/HttpContextAccessor 사용법파일 다운로드1
... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...