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

(시리즈 글이 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




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;
            }
        }
    }
}

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




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







[최초 등록일: ]
[최종 수정일: 10/13/2023]

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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12210정성태4/20/202012533.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202010577오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/20209990Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/20209005스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011304오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208674스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208504스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010545오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202013141개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010929오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011374VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209222오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011991오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011121VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20209047오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010795.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202013070오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209786개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012235개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012567개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208704오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013556개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015878Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208522오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209614오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010324오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...