async(C# 참조)

async 한정자 임을 메서드를 람다 식, 또는 익명 메서드 비동기적으로 수정 된다는 것입니다.이러한 메서드를 비동기 메서드로 라고 합니다.

비동기 메서드는 호출자의 스레드를 차단 하지 않고 잠재적으로 장기 실행 작업을 수행 하는 편리한 방법을 제공 합니다.비동기 메서드의 호출자가 비동기 메서드 완료를 기다리지 않고 작업을 계속 합니다.

[!참고]

async 및 await 키워드는 Visual Studio 2012에 도입 되었습니다.다른 버전의 새로운 기능에 대 한 내용은 Visual Studio 2012 의 새로운 기능.

비동기 프로그래밍에 대 한 소개를 참조 하십시오. Async 및 Await를 사용한 비동기 프로그래밍(C# 및 Visual Basic).

다음 예제에서는 구조를 비동기 이벤트 처리기를 보여 줍니다. StartButton_Click에 비동기 메서드를 호출 하는 ExampleMethodAsync.다운로드 한 웹 사이트의 길이 메서드에서 발생합니다.코드는 Windows Presentation Foundation (WPF) 또는 Windows 저장소 응용 프로그램에 적합합니다.

// In desktop apps that you create by using Visual Studio 2012, you must 
// add a reference and a using directive for System.Net.Http.
// In Windows Store apps, you must add using directives for System.Net.Http 
// and System.Threading.Tasks.

private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // ExampleMethodAsync returns a Task<int> and has an int result.
    // A value is assigned to intTask when ExampleMethodAsync reaches
    // an await.
    try
    {
        Task<int> intTask = ExampleMethodAsync();
        // You can do other work here that doesn't require the result from
        // ExampleMethodAsync. . . .
        // You can access the int result when ExampleMethodAsync completes.
        int intResult = await intTask;
    
        // Or you can combine the previous two steps:
        //int intResult = await ExampleMethodAsync();

        // Process the result (intResult). . . .
    }
    catch (Exception)
    {
        // Process the exception. . . .
    }
}

public async Task<int> ExampleMethodAsync()
{
    var httpClient = new HttpClient();

    // At the await expression, execution in this method is suspended, and
    // control returns to the caller of ExampleMethodAsync.
    // Variable exampleInt is assigned a value when GetStringAsync completes.
    int exampleInt = (await httpClient.GetStringAsync("https://msdn.microsoft.com")).Length;

    // You can break the previous line into several steps to clarify what happens:
    //Task<string> contentsTask = httpClient.GetStringAsync("https://msdn.microsoft.com");
    //string contents = await contentsTask;
    //int exampleInt = contents.Length; 

    // Continue with whatever processing is waiting for exampleInt. . . .

    // After the return statement, any method that's awaiting
    // ExampleMethodAsync can get the integer result.
    return exampleInt;
}
중요중요

비슷한 요소를 사용 하는 전체 WPF 예제를 보려면 연습: Async 및 Await를 사용하여 웹에 액세스(C# 및 Visual Basic).연습 코드를 다운로드할 수 있습니다 개발자 코드 샘플.

일반적으로 메서드를 수정 하는 async 키워드가 하나 이상 포함 되어 있는 기다립니다 식 또는 문.첫 번째에 도달할 때까지 메서드를 동기적으로 실행 await 식에 중단 바뀌게 작업이 완료 될 때까지.한편 컨트롤 메서드 호출자에 게 반환 됩니다.메서드를 포함 하지 않는 경우는 await 식 또는 문에서 그런 동기적으로 실행 합니다.비동기 메서드를 포함 하지 않는 경고 메시지가 컴파일러 경고 await 경우 오류를 나타낼 수 있습니다 때문에.자세한 내용은 컴파일러 경고(수준 1) CS4014을 참조하십시오.

async 키워드는 컨텍스트 키워드입니다.메서드, 람다 식 또는 무명 메서드를 수정 하면 키워드입니다.다른 모든 컨텍스트에서이 식별자로 해석 됩니다.

반환 유형

비동기 메서드는 반환 형식을 가질 수 있습니다 Task, Task<TResult>, 또는 void.모든 메서드를 선언할 수 없습니다 ref 또는 아웃 매개 변수를 이러한 매개 변수가 있는 메서드를 호출할 수 있지만.

지정한 Task<TResult> 비동기 메서드의 반환 형식으로 경우는 반환 문은 메서드의 TResult 형식의 피연산자를 지정 합니다.사용 하 여 Task 메서드가 완료 될 때 의미 있는 값이 없는 반환 된 경우.즉, 호출 하는 메서드를 반환는 Task, 하지만 때의 Task 완료 되 고 모든 await 기다리고 식의 Task void로 평가.

void 반환 형식은 주로 이벤트 처리기를 정의 하는 데 사용 위치는 void 반환 형식이 필요 합니다.Void를 반환 하는 비동기 메서드 호출자가 기다립니다 수 없습니다 및 메서드에서 throw 되는 예외를 catch 할 수 없습니다.

자세한 내용과 예제를 보려면 비동기 반환 형식(C# 및 Visual Basic)을 참조하십시오.

참고 항목

작업

연습: Async 및 Await를 사용하여 웹에 액세스(C# 및 Visual Basic)

참조

await(C# 참조)

AsyncStateMachineAttribute

개념

Async 및 Await를 사용한 비동기 프로그래밍(C# 및 Visual Basic)