Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 5개 있습니다.)

WPF의 Window 객체를 생성했는데 GC 수집 대상이 안 되는 이유

질문이 하나 있군요.

안녕하세요 WPF 에서 Window객체가 가비지 콜렉션에 의해 수집되지 않는거 같아서 문의드립니다.
; https://www.sysnet.pe.kr/3/0/4896

실제로 WPF에서 다음과 같은 간단한 소스 코드로,

using System.Linq;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            foreach (int n in Enumerable.Range(1, 100000))
            {
                Window win = new Window();
            }
        }
    }
}

버튼 클릭 몇 번을 하면 OOM 예외가 발생하도록 만들 수 있습니다. 얼핏 보면 new Window만 했으니 GC 대상이 되어야 하지만 그렇지 않은 현상을 보이는 것입니다.

이런 경우 생각할 여지가 별로 없으니 다행입니다. 수행된 코드는 어차피 생성자 뿐이 없으니 그 안에서 아마도 다른 루트 객체에 자신의 참조를 추가했을 것입니다. 확인을 위해 .NET Reflector 등으로 소스 코드를 확인하면 답이 나오겠지요.

실제로 PresentationFramework 어셈블리의 System.Windows.Window 타입의 생성자를 찾아보면,

[SecurityCritical]
public Window()
{
    this._ownerHandle = IntPtr.Zero;
    this._updateHwndSize = true;
    this._updateHwndLocation = true;
    this._trackMaxWidthDeviceUnits = double.PositiveInfinity;
    this._trackMaxHeightDeviceUnits = double.PositiveInfinity;
    this._windowMaxWidthDeviceUnits = double.PositiveInfinity;
    this._windowMaxHeightDeviceUnits = double.PositiveInfinity;
    this._actualTop = double.NaN;
    this._actualLeft = double.NaN;
    this._dialogOwnerHandle = IntPtr.Zero;
    this._prePanningLocation = new Point(double.NaN, double.NaN);
    SecurityHelper.DemandUnmanagedCode();
    this._inTrustedSubWindow = false;
    this.Initialize();
}

다른 코드는 상관이 없으니 이젠 Initialize를 의심해 볼 수 있습니다.

private void Initialize()
{
    base.BypassLayoutPolicies = true;
    if (this.IsInsideApp)
    {
        if (Application.Current.Dispatcher.Thread == Dispatcher.CurrentDispatcher.Thread)
        {
            this.App.WindowsInternal.Add(this);
            if (this.App.MainWindow == null)
            {
                this.App.MainWindow = this;
            }
        }
        else
        {
            this.App.NonAppWindowsInternal.Add(this);
        }
    }
}

아하... 여기 있군요. WindowsInternal이든 NonAppWindowsInternal이든 자신을 추가하고 있습니다. 이렇게 this.App 객체가 참조를 잡아 두고 있으니 GC 해제가 안된 것입니다.

만약 참조 해제를 하고 싶다면 명시적으로 Close 메서드를 호출해 주면 됩니다.

foreach (int n in Enumerable.Range(1, 100000))
{
    Window win = new Window();
    win.Close();   
}

그런데, 조금 궁금한 부분이 있군요. 왜 WPF 개발팀은 Window 객체에 명시적으로 자원 해제를 위한 IDisposable 인터페이스를 구현하지 않았을까요?




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/19/2017]

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

비밀번호

댓글 작성자
 



2017-09-20 12시25분
[장진국] 친절한 답변 감사합니다^^ 덕분에 궁금중이 해결되었습니다.


[guest]
2017-09-20 02시12분
[이성환] 안녕하세요.

이미 본문에서 잘 설명이 되어 있지만 약간의 사족을 달아봅니다.

WPF 에서는 WindowBase 를 이용한 Window 생성 시 생성되는 모든 Window를
Application 클래스의 WindowsInternal 이라는 WindowsCollection 타입의 컬렉션 프로퍼티에 보관하도록 되어 있습니다.
(본문에 나오는 App 프로퍼티 역시 Window 클래스에서 Application.Current 형태로 보관하는 Application 객체입니다.)

따라서 Window 를 생성하면 Application의 WindowsInternal 에 추가되었다가 Close 되면 제거됩니다.
(본문에서 설명한 것과 같이 Show() 호출이 아니라 new 로 생성하여 Initialize() 가 호출되면 바로 등록됩니다. 그렇기 때문에 생성된 Window는 Close() 호출 전까지 Application에서 참조됩니다.)

Internal 이라는 접미로 알 수 있듯이 이 프로퍼티의 접근제한자는 internal 이며 이 프로퍼티를 public으로 노출하는 것이
Application 클래스의 Windows 라는 프로퍼티 입니다.
이 Windows 프로퍼티는 WindowsInternal을 clone 하여 반환하긴 하지만 Deep copy 가 아니라 컬렉션 객체를 옮겨 담는 형태로 copy됩니다.

사용자는 public으로 노출된 Windows 프로퍼티에 접근해 현재 생성된 Window 들의 정보를 사용할 수 있습니다. (WindowsManager 같은 것을 만들 때 유용합니다.)
이 때 가장 먼저 만들어지는 Window 객체를 Application 클래스의 MainWindow라는 별도의 프로퍼티에 따로 할당하여 사용하는데
이 MainWindow 는 특별한 타입이 아니라 그냥 Window 타입이며 ShutdownMode 같은 영역에 기준으로 사용되기도 합니다.
(MainWindow는 수동으로 재할당이 가능합니다.)

WPF의 Window 관리를 인지하지 못하고 Window 를 생성하여 처리하면 메모리 누수로 이어질 가능성이 높기 때문에 주의가 필요합니다.

여기까지 알아두면 그럭저럭 쓸모있는 사족이었습니다.
[guest]
2017-09-20 09시12분
좋은 내용의 덧글 감사드립니다. ^^
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13605정성태4/23/2024214닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024237오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024343닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024690닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024757닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024778닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024819닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024843닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024812닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241041닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241047닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241065닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241074닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241215C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241189닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241249닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241323Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241105Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241059개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241175Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241433Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241607개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...