Microsoft MVP성태의 닷넷 이야기
닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리 [링크 복사], [링크+제목 복사],
조회: 8516
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 2개 있습니다.)
닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리
; https://www.sysnet.pe.kr/2/0/13688

닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리
; https://www.sysnet.pe.kr/2/0/13695




C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리

문서를 하나 읽다가 문득 아래의 문구에 꽂혔습니다. ^^

Interrupt can interrupt threads that are waiting to enter a lock. On Windows STA threads, waits for locks allow message pumping that can run other code on the same thread during a wait. Some features of the waits can be overridden by a custom SynchronizationContext.


일단, 저 문장을 시작하게 된 Interrupt에 대해서는 전에도 한 번 다룬 적이 있으니 넘어가겠습니다.

재미있는 건 그다음인데요, STA 스레딩 모델일 때 잠금에 대한 대기를 하는 동안 Win32 메시지 루프가 동작할 수 있다는 것입니다. 좀 더 찾아보면,

Which blocking operations cause an STA thread to pump COM messages?
; https://stackoverflow.com/questions/21571598/which-blocking-operations-cause-an-sta-thread-to-pump-com-messages

Is there a way to WAIT for a thread to complete processing while pumping windows messages?
; https://stackoverflow.com/questions/4540244/how-is-this-possible-onpaint-processed-while-in-waitone/4540745#4540745

다음의 메서드는 메시지 펌프 처리를 허용하는 반면,

  • Thread.Join
  • WaitHandle.WaitOne/WaitAny/WaitAll (WaitAll cannot be called from an STA thread though)
  • GC.WaitForPendingFinalizers
  • Monitor.Enter (and therefore lock) - under some conditions
  • ReaderWriterLock
  • BlockingCollection

Thread.Sleep, Console.ReadKey는 메시지 펌프 처리가 안 된다고 합니다. 하지만, 그렇다고 해서 모든 메시지들이 처리되는 것도 아니고 일부 제한적인 메시지만 처리한다고 하는데요, 정말 그런지 확인해 보고 싶어졌습니다. ^^

우선, 허용하는 메시지로는 (Win32 개발자에게는 친숙할 수밖에 없는) WM_PAINT가 있다고 하는데요, 그럼 이걸로 한 번 테스트를 해보겠습니다.

한 가지 문제가 있다면, (Vista 이후) Windows의 경우 Desktop Composition으로 인해 일단 한 번 윈도우가 화면에 그려졌으면 이후 다른 윈도우에 의해 가려지고 다시 나타났다고 해서 WM_PAINT가 발생하지 않는다는 점입니다.

쉽게 말해 WM_PAINT의 발생이 쉽지 않다는 점인데요, 대신 이걸 강제로 발생시킬 수 있는 방법이 있습니다. 즉, offscreen surface를 소유한 dwm.exe 프로세스를 그냥 작업 관리자를 이용해 강제로 종료하면 이후 dwm.exe가 재시작하면서 offscreen surface를 다시 구하기 위해 반드시 응용 프로그램에는 WM_PAINT를 전송하는 과정을 거치게 될 텐데 그걸 이용하면 됩니다.

자, 그럼 코드로 테스트를 해볼까요? ^^

코드는 Windows Forms 기본 프로젝트를 만들고 Monitor.Enter로 잠금을 유지할 스레드 하나와, 그로 인해 동일한 잠금을 획득할 수 없어 블록킹이 발생하는 코드를 수행하도록 버튼에 이벤트 핸들러를 두는 것으로 재현이 가능합니다.

namespace WinFormsApp1;

public partial class Form1 : Form
{
    public const uint WM_PAINT = 0x000F;

    static object s_lock = new();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        new Thread(() =>
        {
            lock (s_lock)
            {
                Thread.Sleep(-1); // 잠금 상태 유지
            }
        })
        { IsBackground = true }.Start();
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_PAINT) // WM_PAINT 발생 유무를 확인하기 위한 용도
        {
            System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - WndProc - WM_PAINT");
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        lock (s_lock) // s_lock을 얻기 위해 무한 대기
        {
            System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - You will never see this message!");
        }
    }
}

테스트 순서는 이렇게 하시면 됩니다.

  1. Visual Studio에서 F5 디버깅 실행
  2. button1 클릭
  3. 작업 관리자에서 dwm.exe 강제 종료
  4. Visual Studio의 Output 창에 "WM_PAINT" 메시지가 출력되는 것을 확인

실제로 해보면 정말 WM_PAINT가 출력되는 것을 확인할 수 있습니다. 게다가 내부의 "그리기" 작업도 끝나 윈도우 화면은 다음과 같이 잘 보입니다.

msg_pump_in_wait_1.png

그렇다면 lock 대신 Thread.Sleep으로 대기를 하도록 바꾸면 어떻게 될까요?

private void button1_Click(object sender, EventArgs e)
{
    //lock (s_lock)
    //{
    //    System.Diagnostics.Trace.WriteLine($"{DateTime.Now} - You will never see this message!");
    //}

    Thread.Sleep(Timeout.Infinite);
}

Q&A 글에 따르면, Thread.Sleep은 메시지 펌핑 처리가 안 된다고 하는데요, 따라서 이전에 수행했던 테스트 과정을 그대로 해보면, Output 창에서 "WM_PAINT" 메시지를 볼 수 없습니다. 게다가 Window 화면도 내부의 "그리기" 작업이 없어 버튼 윈도우 등의 내용이 없습니다.

msg_pump_in_wait_2.png

그다지 유용할 것은 없지만, 테스트를 위한 관련 지식을 통합하는 과정에 묘미가 있을 듯합니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/6/2024]

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

비밀번호

댓글 작성자
 




... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12424정성태11/24/202019569VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202019570.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202017039.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202016159.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202016753오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202017014VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202019174오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202017635오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202018768오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202018295.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202021063VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202019739.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202021742.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202018304오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202019164디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202020819.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202035862도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202020912.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202021849.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202020368.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202020964.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202019046.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202021277.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202020607VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202016599오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202019712.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...