Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)
(시리즈 글이 11개 있습니다.)
디버깅 기술: 6. .NET 예외 처리 정리
; https://www.sysnet.pe.kr/2/0/316

디버깅 기술: 15. First-Chance Exception
; https://www.sysnet.pe.kr/2/0/510

디버깅 기술: 16. Watson Bucket 정보를 이용한 CLR 응용 프로그램 예외 분석
; https://www.sysnet.pe.kr/2/0/595

.NET Framework: 110. WPF - 전역 예외 처리
; https://www.sysnet.pe.kr/2/0/614

디버깅 기술: 42. Watson Bucket 정보를 이용한 CLR 응용 프로그램 예외 분석 - (2)
; https://www.sysnet.pe.kr/2/0/1096

.NET Framework: 534. ASP.NET 응용 프로그램이 예외로 프로세스가 종료된다면?
; https://www.sysnet.pe.kr/2/0/10863

.NET Framework: 538. Thread.Abort로 인해 프로세스가 종료되는 현상
; https://www.sysnet.pe.kr/2/0/10867

디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상
; https://www.sysnet.pe.kr/2/0/11383

디버깅 기술: 119. windbg 분석 사례 - 종료자(Finalizer)에서 예외가 발생한 경우 비정상 종료(Crash) 발생
; https://www.sysnet.pe.kr/2/0/11732

닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
; https://www.sysnet.pe.kr/2/0/13422

닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
; https://www.sysnet.pe.kr/2/0/13551




C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리

간단하게 비동기 함수를 다음과 같이 만들고,

namespace ConsoleApp1;

internal class Program
{
    static async Task Main(string[] args)
    {
        DateTime now = DateTime.Now;
        await DelayAsync(3);
        await DelayAsync(6);
        Console.WriteLine($"{(DateTime.Now - now).TotalSeconds}"); // 3초 + 6초 대기, 총 9초 소요
    }

    static async Task DelayAsync(int id)
    {
        await Task.Delay(id * 1000);
    }
}

호출하면, 총 9초의 시간을 지연시킵니다. 그런데, 저 2개의 비동기 호출을 (종속성이 없어) 병렬 처리하고 싶다면 어떻게 해야 할까요? 그런 경우, 간단하게는 Task.WhenAll을 사용할 수 있습니다.

static async Task Main(string[] args)
{
    DateTime now = DateTime.Now;

    Task t1 = DelayTask(3); // 3초 작업 시작
    Task t2 = DelayAsync(6); // 연이어 6초 작업 시작

    await Task.WhenAll(t1, t2); // 6초 소요

    Console.WriteLine($"{(DateTime.Now - now).TotalSeconds}");
}

하지만, WhenAll을 사용하지 않고 다음과 같이 표현하는 것도 가능합니다.

static async Task Main(string[] args)
{
    DateTime now = DateTime.Now;

    Task t1 = DelayTask(3); // 3초 작업 시작
    Task t2 = DelayAsync(6); // 연이어 6초 작업 시작

    await t1; // 3초 대기
    await t2; // 위의 3초 대기를 포함해 3초 더 대기, 총 6초 소요

    Console.WriteLine($"{(DateTime.Now - now).TotalSeconds}");
}

마찬가지로 await 순서를 바꿔도 상관없습니다.

await t2; // 6초 대기
await t1; // 위의 6초 대기 동안에 t1은 이미 종료했으므로 바로 반환

그렇다면 개별 await를 한 것과 WhenAll을 호출한 것과는 어떤 차이가 있을까요? ^^




그에 대한 차이점은 await 코드를 원칙적으로 분석하시면 됩니다.

await t1; // t1 작업 대기 후 아래의 코드 실행
await t2; 

위와 같은 상황에서 t1의 작업에서 예외가 발생하면 throw가 되므로 그다음 코드인 "await t2"를 수행하지 않게 됩니다. 이런 차이점을 try/catch로 감싸면 좀 더 명확하게 알 수 있습니다.

namespace ConsoleApp1;

internal class Program
{
    static async Task Main(string[] args)
    {
        DateTime now = DateTime.Now;

        Task t1 = DelayAsync(3);
        Task t2 = DelayAsync(6);

        try
        {
            await t1;
            await t2;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.WriteLine($"t1.Exception: {t1.Exception}");
            Console.WriteLine($"t2.Exception: {t2.Exception}");
        }

        Console.WriteLine($"{(DateTime.Now - now).TotalSeconds}");
    }

    static async Task DelayAsync(int id)
    {
        await Task.Delay(id * 1000);
        throw new InvalidOperationException($"{id} - Exception in DelayAsync");
    }
}

/* 실행 결과
System.InvalidOperationException: 3 - Exception in DelayAsync
   at ConsoleApp1.Program.DelayAsync(Int32 id) in C:\temp\ConsoleApp1\Program.cs:line 71
   at ConsoleApp1.Program.Main(String[] args) in C:\temp\ConsoleApp1\Program.cs:line 17
t1.Exception: System.AggregateException: One or more errors occurred. (3 - Exception in DelayAsync)
 ---> System.InvalidOperationException: 3 - Exception in DelayAsync
   at ConsoleApp1.Program.DelayAsync(Int32 id) in C:\temp\ConsoleApp1\Program.cs:line 71
   at ConsoleApp1.Program.Main(String[] args) in C:\temp\ConsoleApp1\Program.cs:line 17
   --- End of inner exception stack trace ---
t2.Exception:
3.0295292
*/

위의 결과를 보면 await t1에서의 예외로 인해 3초 만에 실행이 종료됩니다. 이와 함께 "Exception e"는 "await t1"의 예외로 설정되고, 개별 t1.Exception은 System.AggregateException 타입으로 예외 정보를 갖게 됩니다.

그런 반면 t2.Exception은 비어 있는데요, 그렇다고 저 정보가 실행이 안 되었기 때문에 빈 것은 아닙니다. 애당초 "Task t2 = DelayAsync(6);" 코드를 호출하는 단계에서 비동기 작업은 시작했으므로, 별도로 이를 확인하기 위해 다음과 같이 Sleep을 주면,

try
{
    await t1;
    await t2;
}
catch (Exception e)
{
    Console.WriteLine(e);
    Console.WriteLine($"t1.Exception: {t1.Exception}");
    Console.WriteLine($"t2.Exception: {t2.Exception}"); // 이 시점에는 작업이 진행되지 않아 비어 있지만,
}

Thread.Sleep(3000);
Console.WriteLine($"t2.Exception(2nd): {t2.Exception}"); // 이 시점에는 6초 대기가 끝나 예외 정보가 채워져 있음.

/* 출력 결과
...[생략]...

t2.Exception:
t2.Exception(2nd): System.AggregateException: One or more errors occurred. (6 - Exception in DelayAsync)
 ---> System.InvalidOperationException: 6 - Exception in DelayAsync
   at ConsoleApp1.Program.DelayAsync(Int32 id) in C:\temp\ConsoleApp1\Program.cs:line 71
   --- End of inner exception stack trace ---

보는 바와 같이 두 번째 출력에서 t2의 Exception 필드에 AggregateException 예외 정보가 채워져 있는 것을 확인할 수 있습니다.

반면 위의 코드를 Task.WhenAll로 바꾸면,

Task t1 = DelayAsync(3);
Task t2 = DelayAsync(6);

try
{
    await Task.WhenAll(t1, t2); // (3초가 아닌) 6초 대기 후,
}
catch (Exception e)
{
    Console.WriteLine(t1.Exception);
    Console.WriteLine(t2.Exception);
}

/* 출력 결과:
System.AggregateException: One or more errors occurred. (3 - Exception in DelayAsync)
 ---> System.InvalidOperationException: 3 - Exception in DelayAsync
   at ConsoleApp1.Program.DelayAsync(Int32 id) in C:\temp\ConsoleApp1\Program.cs:line 71
   at ConsoleApp1.Program.Main(String[] args) in C:\temp\ConsoleApp1\Program.cs:line 50
   --- End of inner exception stack trace ---
System.AggregateException: One or more errors occurred. (6 - Exception in DelayAsync)
 ---> System.InvalidOperationException: 6 - Exception in DelayAsync
   at ConsoleApp1.Program.DelayAsync(Int32 id) in C:\temp\ConsoleApp1\Program.cs:line 71
   --- End of inner exception stack trace ---
*/

모든 비동기 작업이 끝난 후에 처리를 이어가므로, 각각의 Task에 대한 예외 정보가 모두 기록돼 있습니다. 차이점이 눈에 들어오시죠? ^^ 따라서 굳이 Task.WhenAll을 개별 await으로 바꿔 쓰고 싶다면 이런 식으로 처리할 수는 있습니다.

// Task WhenAll의 코드를 직접 구성하는 경우

try
{
    Exception? e1 = null, e2 = null;

    try
    {
        await t1;
    }
    catch (Exception e)
    {
        e1 = e;
    }

    try
    {
        await t2;
    }
    catch (Exception e)
    {
        e2 = e;
    }

    if (e1 != null)
    {
        throw e1;
    }

    if (e2 != null)
    {
        throw e2;
    }
}
catch (Exception e)
{
    Console.WriteLine($"t1.Exception: {t1.Exception}");
    Console.WriteLine($"t2.Exception: {t2.Exception}");
}

음... 그냥 차라리 Task.WhenAll 쓰는 것이 더 낫겠습니다.




지난 글에서,

C# - 비동기 메서드의 async 예약어 유무에 따른 차이
; https://www.sysnet.pe.kr/2/0/13421

awaitable 메서드를 정의하는 2가지 방식을 설명했는데요, 이게 예외랑 역이면 약간 혼란스러울 수 있습니다. 예를 들어, 위에서 적용한 방식대로 다음과 같이 코딩을 하면,

namespace ConsoleApp1;

internal class Program
{
    static async Task Main(string[] args)
    {
        DateTime now = DateTime.Now;

        Task t1 = DelayTask(3);
        Task t2 = DelayAsync(6);

        try
        {
            await Task.WhenAll(t1, t2);
        }
        catch (Exception e)
        {
            Console.WriteLine(t1.Exception);
            Console.WriteLine(t2.Exception);
        }

        Console.WriteLine($"{(DateTime.Now - now).TotalSeconds}");
    }

    static Task DelayTask(int id)
    {
        Task task = Task.Delay(3000);
        throw new ApplicationException($"{id} - Exception in DelayTask");
        return task;
    }

    static async Task DelayAsync(int id)
    {
        await Task.Delay(id * 1000);
        throw new InvalidOperationException($"{id} - Exception in DelayAsync");
    }
}

/* 출력 결과:
Unhandled exception. System.ApplicationException: 3 - Exception in DelayTask
   at ConsoleApp1.Program.DelayTask(Int32 id) in C:\temp\ConsoleApp2\Program.cs:line 31
   at ConsoleApp1.Program.Main(String[] args) in C:\temp\ConsoleApp2\Program.cs:line 12
   at ConsoleApp1.Program.<Main>(String[] args)
*/

이번에는 3초의 대기조차 없이 곧바로 System.ApplicationException 예외가 발생하면서 (try/catch를 했는데도) 비정상 종료를 하게 됩니다. 그도 그럴 것이, DelayTask를 호출하는 시점에 내부 코드는 Task.Delay를 곧바로 실행한 후 "throw ..."를 하기 때문입니다.

따라서 try의 시점을 앞당겨야 하는데,

Task t1;
Task t2;

try
{
    t1 = DelayTask(3);
    t2 = DelayAsync(6);

    await Task.WhenAll(t1, t2);
}
catch (Exception e)
{
    Console.WriteLine(t1.Exception);
    Console.WriteLine(t2.Exception);
}

이와 상관없이 DelayTask에서 await 처리를 하지 않은 체 예외가 발생했으므로 t2까지 가지 못하고 예외가 발생한다는 점에는 변함이 없습니다.

어찌 보면 DelayTask의 내부 구현 코드를 감안했을 때 이것이 당연하다고 할 수 있지만, 호출하는 입장에서라면 완전히 다른 문제가 됩니다. 즉, 동일한 awaitable 메서드임에도 불구하고 내부 구현에 따라 외부의 예외 처리를 달리해야 한다는 것은 분명 문제라고 볼 수 있습니다. 이런 문제를 피하려면 대상 awaitable 메서드가 단순히 Task를 반환하는 유형인지, async가 붙은 유형인지 확인해야 하는 절차를 거쳐야 합니다. 게다가 이것 역시 "인터페이스"처럼 계약 관계가 되므로 async를 부여했던 메서드를 나중에 Task로 간략화하는 것에 주의해야 한다는 문제도 함께 있습니다.

결국, 지난 글에서는 효율상 할 수만 있다면 Task를 바로 반환하는 것을 권장했지만, 외부에서의 일관성 있는 예외 처리까지 감안한다면 가능한 async로 통일하는 것이 나을 수도 있습니다.

여러분의 선택은 어떤가요? ^^ DelayTask 유형처럼 만들 수 있는 상황에서 DelayAsync 유형처럼 만드실 건가요? ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/20/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)
13435정성태11/6/20232979닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232763스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232466스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232544오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232900스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232742닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233017닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233096닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233303닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233462스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233233닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233213스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233354닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233437닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235680스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233257스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233952닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233486닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233285오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233786닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233553디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233744닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237041닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233536Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235071닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233914닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...