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)
13272정성태2/27/20234218오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234150오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233762.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234301스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20234849개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234775.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234382오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234303.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20235802스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20233944개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235009디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234302Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234089오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234222.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234119오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234205.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235057개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234352오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234263Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235044Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20233856오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234318스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236116오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20234932오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234050오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20234962VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...