Microsoft MVP성태의 닷넷 이야기
.NET Framework: 732. C# - Task.ContinueWith 설명 [링크 복사], [링크+제목 복사],
조회: 26249
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - Task.ContinueWith 설명

Task 타입에 제공되는 ContinueWith 메서드는 Task의 본래 작업이 완료된 후 실행될 작업을 등록하는 기능을 제공합니다. 가령 다음과 같이 코딩을 하면,

Task<int> task = new Task<int>(() =>
{
    Console.WriteLine("TEST0");
    Thread.Sleep(5000);
    return 1;
});

task.Start();

task.ContinueWith((arg) =>
{
    Console.WriteLine("TEST1");
});

화면에는 "TEST0"에 이어 5초 후 "TEST1"이 출력됩니다. 그런데, 이 코드를 보면서 몇 가지 궁금함이 생깁니다.

  1. 원래의 작업을 마친 Task의 스레드는 ContinueWith로 등록된 메서드를 이어서 실행해 주는 걸까?
  2. 만약 이어서 실행하는 거라면 Task의 작업이 이미 종료된 경우라면 어떨까?

우선 위의 질문에 대해 2번부터 확인해 보겠습니다. 방법은, 간단하게 다음과 같이 코딩해 보면 됩니다. ^^

Task<int> task = new Task<int>(() =>
{
    Console.WriteLine("TEST0");
    Thread.Sleep(5000);
    return 1;
});

task.Start();
Thread.Sleep(6000); // task 작업이 완료될 수 있도록.

task.ContinueWith((arg) =>
{
    Console.WriteLine("TEST1");
});

확인 결과, Task의 원래 작업이 종료된 이후에도 ContinueWith는 잘 실행됩니다. 그럼, 또 궁금해집니다. 이미 Task의 스레드는 Thread Pool에 반환된 상태인데, 저런 경우라면 ContinueWith를 호출한 스레드가 그냥 이어서 실행하는 것인지, 아니면 그것도 결국 Thread Pool에 맡기는 것인지?

역시 이것도 테스트해 보면 알 수 있습니다.

...
{
    Task<int> task = new Task<int>(() =>
    {
        WriteLog("TEST0");
        Thread.Sleep(5000);
        return 1;
    });

    task.Start();

    task.ContinueWith((arg) =>
    {
        WriteLog("TEST1");
    });

    Thread.Sleep(6000); // task 작업이 완료될 수 있도록.

    task.ContinueWith((arg) =>
    {
        WriteLog("TEST2");
    });
}

private static void WriteLog(string text)
{
    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] " + text);
}

확인 결과, ContinueWith는 원본 Task의 작업 종료 여부에 상관없이 Thread Pool로부터 할당받은 스레드에 의해서 실행됩니다.




ContinueWith로 지정한 작업을 다음과 같은 조건으로 실행할 수도 있습니다.

  • Task의 작업이 종료되지 않은 경우, 그 스레드에서 이어서 실행
  • Task의 작업이 종료된 경우, ContinueWith를 호출한 스레드에서 실행

방법은, 다음과 같이 TaskContinuationOptions.ExecuteSynchronously 옵션을 주면 됩니다.

{
    Task<int> task = new Task<int>(() =>
    {
        WriteLog("TEST0");
        Thread.Sleep(5000);
        return 1;
    });

    task.Start();

    task.ContinueWith((arg) =>
    {
        WriteLog("TEST1"); // task에 할당된 스레드에 의해 실행
    }, TaskContinuationOptions.ExecuteSynchronously);

    Console.WriteLine(task.IsCompleted);
    Thread.Sleep(6000);
    Console.WriteLine(task.IsCompleted);

    task.ContinueWith((arg) =>
    {
        WriteLog("TEST2"); // ContinueWith를 호출한 현재 스레드에 의해 실행
    }, TaskContinuationOptions.ExecuteSynchronously);

    Console.ReadLine();
}

참고로 TaskContinuationOptions으로 제공할 수 있는 옵션은 다음과 같습니다.

public enum TaskContinuationOptions
{
    None = 0,
    PreferFairness = 1,
    LongRunning = 2,
    AttachedToParent = 4,
    DenyChildAttach = 8,
    HideScheduler = 16,
    LazyCancellation = 32,
    RunContinuationsAsynchronously = 64,
    NotOnRanToCompletion = 65536,
    NotOnFaulted = 131072,
    OnlyOnCanceled = 196608,
    NotOnCanceled = 262144,
    OnlyOnFaulted = 327680,
    OnlyOnRanToCompletion = 393216,
    ExecuteSynchronously = 524288
}

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

따라서, 지난번에 구현했던 사용자 정의 awaitable 타입인 MyTask/MyTaskAwaiter의 동작 방식은 TaskContinuationOptions.ExecuteSynchronously 옵션을 설정한 것과 같습니다.




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







[최초 등록일: ]
[최종 수정일: 7/13/2021]

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

비밀번호

댓글 작성자
 



2021-05-05 12시27분
[한예지] 쉬운 설명 감사드립니다~!
[guest]

... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12128정성태1/26/202023091오류 유형: 591. The code execution cannot proceed because mfc100.dll was not found. Reinstalling the program may fix this problem.
12127정성태1/25/202020214.NET Framework: 881. C# DLL에서 제공하는 Win32 export 함수의 내부 동작 방식(VT Fix up Table)파일 다운로드1
12126정성태1/25/202022689.NET Framework: 880. C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석파일 다운로드1
12125정성태1/24/202020896VS.NET IDE: 141. IDE0019 - Use pattern matching
12124정성태1/23/202022651VS.NET IDE: 140. IDE1006 - Naming rule violation: These words must begin with upper case characters: ...
12123정성태1/23/202023507웹: 39. Google Analytics - gtag 함수를 이용해 페이지 URL 수정 및 별도의 이벤트 생성 방법 [2]
12122정성태1/20/202020217.NET Framework: 879. C/C++의 UNREFERENCED_PARAMETER 매크로를 C#에서 우회하는 방법(IDE0060 - Remove unused parameter '...')파일 다운로드1
12121정성태1/20/202019094VS.NET IDE: 139. Visual Studio - Error List: "Could not find schema information for the ..."파일 다운로드1
12120정성태1/19/202023478.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)파일 다운로드1
12119정성태1/17/202023955디버깅 기술: 160. Windbg 확장 DLL 만들기 (3) - C#으로 만드는 방법
12118정성태1/17/202024720개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기 [1]
12117정성태1/15/202022997디버깅 기술: 159. C# - 디버깅 중인 프로세스를 강제로 다른 디버거에서 연결하는 방법파일 다운로드1
12116정성태1/15/202024622디버깅 기술: 158. Visual Studio로 디버깅 시 sos.dll 확장 명령어를 (비롯한 windbg의 다양한 기능을) 수행하는 방법
12115정성태1/14/202024617디버깅 기술: 157. C# - PEB.ProcessHeap을 이용해 디버깅 중인지 확인하는 방법파일 다운로드1
12114정성태1/13/202025353디버깅 기술: 156. C# - PDB 파일로부터 심벌(Symbol) 및 타입(Type) 정보 열거 [1]파일 다운로드3
12113정성태1/12/202025817오류 유형: 590. Visual C++ 빌드 오류 - fatal error LNK1104: cannot open file 'atls.lib' [1]
12112정성태1/12/202019844오류 유형: 589. PowerShell - 원격 Invoke-Command 실행 시 "WinRM cannot complete the operation" 오류 발생
12111정성태1/12/202024040디버깅 기술: 155. C# - KernelMemoryIO 드라이버를 이용해 실행 프로그램을 숨기는 방법(DKOM: Direct Kernel Object Modification) [16]파일 다운로드1
12110정성태1/11/202025182디버깅 기술: 154. Patch Guard로 인해 블루 스크린(BSOD)가 발생하는 사례 [5]파일 다운로드1
12109정성태1/10/202020328오류 유형: 588. Driver 프로젝트 빌드 오류 - Inf2Cat error -2: "Inf2Cat, signability test failed."
12108정성태1/10/202021474오류 유형: 587. Kernel Driver 시작 시 127(The specified procedure could not be found.) 오류 메시지 발생
12107정성태1/10/202023688.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
12106정성태1/8/202022588VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202020974디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202024418DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202027615DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
... [76]  77  78  79  80  81  82  83  84  85  86  87  88  89  90  ...