Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 11개 있습니다.)
.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

닷넷: 2278. WPF - 스레드에 종속되는 DependencyObject
; https://www.sysnet.pe.kr/2/0/13682

닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법
; https://www.sysnet.pe.kr/2/0/13743




Console/Service Application을 위한 SynchronizationContext - AsyncContext

일반적으로 WPF/WinForm 프로그램을 하면서 SynchronizationContext를 접하게 되는데요, 사실 마이크로소프트가 제공해주는 기본 클래스에 불과하고 WPF는 DispatcherSynchronizationContext로, WinForm은 WindowsFormsSynchronizationContext로 하위 클래스를 정의하는 방식입니다.

즉, Console 응용 프로그램이나 NT Service 프로그램을 위해서 정의할 수 있지만 일단은 마이크로소프트에서 그런 환경을 위한 SynchronizationContext는 만들지 않았을 뿐입니다. 그렇다면 당연히, 만들면 됩니다. ^^ 그리고 실제로 그걸 다음의 라이브러리에서 제공하고 있습니다.

StephenCleary / AsyncEx
; https://github.com/StephenCleary/AsyncEx

Install-Package Nito.AsyncEx -Version 5.0.0

위의 라이브러리에서 SynchronizationContext를 구현한 타입은 AsyncContext인데,

AsyncContext
; https://github.com/StephenCleary/AsyncEx/wiki/AsyncContext

링크에서 설명한 바와 같이 AsyncContext.Run을 통해 실행한 이후부터는,

class Program
{
  static async Task<int> AsyncMain()
  {
    // ... 이 내부에서 SynchronizationContext가 제공됨
  }

  static int Main(string[] args)
  {
    return AsyncContext.Run(AsyncMain);
  }
}

SynchronizationContext가 해당 스레드 문맥에 제공되므로 Post/Send 메서드로 SynchronizationContext의 기능을 수행할 수 있습니다.




그런데, 사실 Console 응용 프로그램 등에서 저걸 써야 할 상황이 얼마나 있을까? 하는 의문이 듭니다. 만약 써야 한다면, 아마도 멋들어진 CUI를 구현해 그것을 UI로 두고 동기화를 지키는 용도로 쓰면 될 테지만... 글쎄요, 분명 활용도가 많지 않아 보입니다. (마이크로소프트가 만들어 두지 않은 이유일 것입니다.)

그래도 저 같은 사람한테는 편한 용도가 하나 있긴 합니다. 가령, 다음과 같은 글을 쓰면서,

WebClient 타입의 ...Async 메서드 호출은 왜 await + 동기 호출 시 hang 현상이 발생할까요?
; https://www.sysnet.pe.kr/2/0/11419

재현 코드를 만들기 위해 프로젝트 유형을 Windows Forms로 했는데, 이제는 그냥 AsyncEx를 참조해 콘솔 응용 프로그램으로도 간단한 재현 프로그램을 만들 수 있게 되었습니다. ^^ 실제로 다음의 코드는 "WebClient 타입의 ...Async 메서드 호출은 왜 await + 동기 호출 시 hang 현상이 발생할까요?" 글에 실은 예제와 정확히 동일한 hang 현상을 겪습니다.

using Nito.AsyncEx;
using System;
using System.Net;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    // Install-Package Nito.AsyncEx -Version 5.0.0
    class Program
    {
        static void Main(string[] args)
        {
            AsyncContext.Run(AsyncMain);
        }

        static async Task<int> AsyncMain()
        {
            Uri uri = new Uri("https://www.naver.com");

            Task<string> textTask = GetHtmlTextAsync(uri);

            string result = textTask.Result; // hang 현상 발생함.
            return 0;
        }

        public static async Task<string> GetHtmlTextAsync(Uri uri)
        {
            var client = new WebClient();
            {
                string result = await client.DownloadStringTaskAsync(uri).ConfigureAwait(false);
                return result;
            }
        }
    }
}

뭐... 딱 그 정도... 활용 사례입니다. ^^;




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







[최초 등록일: ]
[최종 수정일: 9/26/2024]

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)
14027정성태10/15/2025473닷넷: 2371. C# - CRC64 (System.IO.Hashing의 약식 버전)파일 다운로드1
14026정성태10/15/2025500닷넷: 2370. 닷넷 지원 정보의 "package-provided" 의미
14025정성태10/14/2025776Linux: 126. eBPF (bpf2go) - tcp_sendmsg 예제
14024정성태10/14/2025811오류 유형: 984. Whisper.net - System.Exception: 'Cannot dispose while processing, please use DisposeAsync instead.'
14023정성태10/12/20251237닷넷: 2369. C# / Whisper 모델 - 동영상의 음성을 인식해 자동으로 SRT 자막 파일을 생성 [1]파일 다운로드1
14022정성태10/10/20252101닷넷: 2368. C# / NAudio - (AI 학습을 위해) 무음 구간을 반영한 오디오 파일 분할파일 다운로드1
14021정성태10/6/20252665닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [1]파일 다운로드1
14020정성태10/2/20252302Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례
14019정성태10/1/20252434Linux: 124. eBPF - __sk_buff / sk_buff 구조체
14018정성태9/30/20251799닷넷: 2366. C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법파일 다운로드1
14017정성태9/29/20252262Linux: 123. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
14016정성태9/28/20252539Linux: 122. eBPF - __attribute__((preserve_access_index)) 사용법
14015정성태9/22/20251982닷넷: 2365. C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제파일 다운로드1
14014정성태9/17/20251968닷넷: 2364. C# - stun.l.google.com을 사용해 공용 IP 주소와 포트를 알아내는 방법파일 다운로드1
14013정성태9/14/20252610닷넷: 2363. C# - Whisper.NET Library를 이용해 음성을 텍스트로 변환 및 번역하는 예제파일 다운로드1
14012정성태9/9/20252862닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20253494닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20253314오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20253776닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20254353닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20254762닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20255053Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20254028오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20254614오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20254879닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...