Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 10개 있습니다.)
(시리즈 글이 9개 있습니다.)
.NET Framework: 612. UWP(유니버설 윈도우 플랫폼) 앱에서 콜백 함수 내에서의 UI 요소 접근 방법
; https://www.sysnet.pe.kr/2/0/11071

.NET Framework: 680. C# - 작업자(Worker) 스레드와 UI 스레드
; https://www.sysnet.pe.kr/2/0/11287

.NET Framework: 777. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서!
; https://www.sysnet.pe.kr/2/0/11561

.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)
; https://www.sysnet.pe.kr/2/0/11802

.NET Framework: 886. C# - Console 응용 프로그램에서 UI 스레드 구현 방법
; https://www.sysnet.pe.kr/2/0/12139

.NET Framework: 911. Console/Service Application을 위한 SynchronizationContext - AsyncContext
; https://www.sysnet.pe.kr/2/0/12231

.NET Framework: 1022. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12537

.NET Framework: 2076. C# - SynchronizationContext 기본 사용법
; https://www.sysnet.pe.kr/2/0/13190

.NET Framework: 2077. C# - 직접 만들어 보는 SynchronizationContext
; https://www.sysnet.pe.kr/2/0/13191




C# - Console 응용 프로그램에서 UI 스레드 구현 방법

이 글과 관련된 영상을 유튜브로 제공하고 있습니다. ^^

닷넷 프로그램 실습 #4 콘솔 응용 프로그램의 메시지 루프 (2분 영상)
; https://youtu.be/gOJw_zTki7c



그러고 보니 UI 스레드를 설명하면서,

C# - 작업자 스레드와 UI 스레드
; https://www.sysnet.pe.kr/2/0/11287

Windows Forms/WPF에서만 사용 예를 살펴봤는데, 사실 콘솔 응용 프로그램에서도 가능합니다. 그저 메시지 루프만 가지면 되기 때문입니다.

while (true)
{
    int ret = NativeMethods.GetMessage(out MSG msg, IntPtr.Zero, 0, 0);
    if (ret == 0 || ret == -1)
    {
        break;
    }

    NativeMethods.TranslateMessage(ref msg);
    NativeMethods.DispatchMessage(ref msg);
}

이렇게 메시지 루프를 구현하고 있을 콘솔 응용 프로그램의 스레드에서, 한 가지 문제라면 "Window" 자원을 갖지 않아 해당 메시지 루프로는 PostMessage나 SendMessage를 통해서는 메시지를 보낼 수 없다는 점입니다. 대신 HWND가 아닌 Thread ID를 통해 메시지를 보낼 수 있는 PostThreadMessage라는 API를 사용해야 합니다.

PostThreadMessageA function
; https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postthreadmessagea

그리고 이런저런 기능을 추가하다 보면 다음과 같은 식으로 MessageLoop를 만들 수 있고,

using System;
using System.Threading;

namespace CustomMessageLoop
{
    public class MessageLoop : IDisposable
    {
        uint _tid;
        EventWaitHandle _ewh_Sync = new EventWaitHandle(true, EventResetMode.ManualReset);
        EventWaitHandle _ewh_Exit = new EventWaitHandle(true, EventResetMode.ManualReset);

        public ApartmentState COMApartment => _uiThread.GetApartmentState();

        public void PostMessage(Win32Message msg)
        {
            PostMessage((uint)msg);
        }

        bool _disposed;

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed == false)
            {
                if (disposing == true)
                {
                    SendMessage(Win32Message.WM_CLOSE);
                    _ewh_Exit.WaitOne();
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void PostMessage(uint msg)
        {
            if (_tid == 0)
            {
                return;
            }

            NativeMethods.PostThreadMessage(_tid, msg, UIntPtr.Zero, IntPtr.Zero);
        }

        public void WaitForExit(int millisecondsTimeout = Timeout.Infinite)
        {
            _ewh_Exit.WaitOne(millisecondsTimeout);
        }

        public void SendMessage(Win32Message msg)
        {
            SendMessage((uint)msg);
        }

        public void SendMessage(uint msg)
        {
            if (_tid == 0)
            {
                return;
            }

            _ewh_Sync.Reset();
            NativeMethods.PostThreadMessage(_tid, msg, UIntPtr.Zero, IntPtr.Zero);
            _ewh_Sync.WaitOne();
        }

        Thread _uiThread;
        bool _useBackgroundThread;
        ApartmentState _apartment;

        public MessageLoop() : this(true, ApartmentState.STA) { }

        public MessageLoop(bool useBackgroundThread) : this(useBackgroundThread, ApartmentState.STA) { }

        public MessageLoop(bool useBackgroundThread, ApartmentState apartment)
        {
            _useBackgroundThread = useBackgroundThread;
            _apartment = apartment;
        }

        public void Run()
        {
            _ewh_Exit.Reset();

            _uiThread = new Thread(Start);
            _uiThread.SetApartmentState(_apartment);
            _uiThread.IsBackground = _useBackgroundThread;
            _uiThread.Start();
        }

        public event EventHandler Loaded;
        public event EventHandler Closed;
        public event EventHandler<MessageEventArgs> MessageArrived;

        protected virtual void OnLoad() { }

        protected virtual void OnClose() { }

        protected virtual void WindowProc(MSG msg) { }

        void Start()
        {
            _tid = NativeMethods.GetCurrentThreadId();

            OnLoad();
            Loaded?.Invoke(this, EventArgs.Empty);

            try
            {
                while (true)
                {
                    int ret = NativeMethods.GetMessage(out MSG msg, IntPtr.Zero, 0, 0);
                    if (ret == 0 || ret == -1)
                    {
                        break;
                    }

                    try
                    {
                        WindowProc(msg);
                        MessageArrived?.Invoke(this, new MessageEventArgs(msg));

                        switch (msg.message)
                        {
                            case (uint)Win32Message.WM_CLOSE:
                                OnClose();
                                Closed?.Invoke(this, EventArgs.Empty);
                                return;
                        }

                        NativeMethods.TranslateMessage(ref msg);
                        NativeMethods.DispatchMessage(ref msg);
                    }
                    finally
                    {
                        _ewh_Sync.Set();
                    }
                }
            }
            finally
            {
                _disposed = true;
                _tid = 0;
                _ewh_Exit.Set();
            }
        }
    }
}

이런 식으로 사용할 수 있습니다.

using CustomMessageLoop;
using System;

class Program
{
    // Install-Package CustomMessageLoop
    static void Main(string[] args)
    {
        using (MessageLoop mml = new MessageLoop())
        {
            mml.Loaded += Mml_Loaded;
            mml.Closed += Mml_Closed;

            mml.Run();

            Console.ReadLine();
        }
    }

    private static void Mml_Loaded(object sender, EventArgs e)
    {
        Console.WriteLine("Mml_Loaded");
    }

    private static void Mml_Closed(object sender, EventArgs e)
    {
        Console.WriteLine("Mml_Closed");
    }
}

MessageLoop 소스 코드는 github 프로젝트(DotNetSamples/WinConsole/UIThread/CustomMessageLoop/)에 있습니다.




그런데, 사실 따지고 보면 저렇게 HWND 없이 구현하는 메시지 루프가 크게 장점이 없습니다. 대개의 경우 저런 식으로 부가 코드를 넣기 보다 차라리 간단하게 System.Windows.Forms 어셈블리를 추가해 Visual Studio의 WinForm 디자이너 혜택까지 누리며 Application.Run으로 구현하는 것이 더 좋을 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/25/2023]

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)
13248정성태2/7/20234052오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20234965VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234094개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234642.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20233998VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234860디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234305디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233829디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20233988디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233630디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235646.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235336.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20234973개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234521개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235563개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20236909오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234707스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233622오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234034개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20234978.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235120.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234827개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234499.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233750개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234102Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234288오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...