728x90

📘 개념 요약

비동기 메서드는 기본적으로 async와 await 키워드를 사용하여 비동기적으로 실행됩니다. 하지만 콘솔 앱이나 초기 Main() 함수 등에서는 비동기 메서드를 동기 방식으로 실행해야 할 때가 있습니다.

이를 위해 사용하는 대표적인 방법이 다음 두 가지입니다:

  1. Task.Wait()
  2. Task.GetAwaiter().GetResult()

🧠 용어 설명

용어 설명
Task 비동기 작업을 나타내는 .NET 객체. Task<T>는 반환값 포함
Wait() 비동기 작업을 블로킹 방식으로 기다림
GetAwaiter().GetResult() 비동기 작업의 결과를 예외 래핑 없이 직접 가져옴
AggregateException Wait() 사용 시 예외가 감싸져 반환되는 타입
데드락(Deadlock) UI 스레드가 기다리는 동안 자신이 필요한 작업도 못 하게 되어 무한 대기하는 상태
 

💻 예제 1 – DownloadDataAsync().Wait();

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    public static async Task DownloadDataAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            string result = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts/1");
            Console.WriteLine("응답 데이터:");
            Console.WriteLine(result);
        }
    }

    static void Main(string[] args)
    {
        try
        {
            // 비동기 메서드를 동기적으로 대기
            DownloadDataAsync().Wait();  
        }
        catch (AggregateException ex)
        {
            Console.WriteLine($"예외 발생: {ex.InnerException?.Message}");
        }
    }
}

✅ 특징:

  • Wait()은 현재 스레드를 멈춰서 기다림
  • 예외 발생 시 AggregateException으로 감싸짐

💻 예제 2 – DownloadDataAsync().GetAwaiter().GetResult();

static void Main(string[] args)
{
    try
    {
        // 비동기 메서드를 동기적으로 결과 획득
        DownloadDataAsync().GetAwaiter().GetResult();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"예외 발생: {ex.Message}");
    }
}

✅ 특징:

  • .GetAwaiter().GetResult()는 예외를 감싸지 않고 직접 던짐
  • Wait()보다 디버깅 시 유리함

🔧 언제 어떤 걸 써야 할까?

상황추천 방식이유
콘솔 앱에서 한 번만 실행 Wait() 간단함
예외 디버깅이 중요할 때 GetResult() 원본 예외 확인 가능
UI 앱 (WPF, WinForms, ASP.NET 등) ❌ 사용 지양 데드락 발생 가능성
C# 7.1 이상 & Main 함수 async Task Main() 가장 안전하고 권장
// C# 7.1 이상에서 가장 좋은 방법
static async Task Main(string[] args)
{
    await DownloadDataAsync();
}

📝 핵심 정리

 

항목 .Wait() .GetAwaiter() GetResult()
예외 전달 AggregateException로 감싸짐 원래 예외 그대로 전달
코드 가독성 간단함 다소 복잡함
디버깅 불편 유리
데드락 위험 있음 있음
콘솔 앱 사용 가능 가능
UI 앱 사용 비추천 비추천
 

🏷 추천 태그

C#, 비동기, Task, async await, GetAwaiter, Wait, 예외처리, 콘솔앱, UI 데드락, 프로그래밍 기초, 동기 vs 비동기, 코드 분석

728x90

+ Recent posts