다음을 통해 공유


Await 연산자(Visual Basic)

비동기 메서드 또는 람다 식의 피연산자에 연산자를 적용 Await 하여 대기 중인 작업이 완료될 때까지 메서드 실행을 일시 중단합니다. 작업은 진행 중인 작업을 나타냅니다.

사용되는 메서드 Await 에는 비동 기 한정자가 있어야 합니다. 한정자를 사용하여 Async 정의되고 일반적으로 하나 이상의 Await 식을 포함하는 이러한 메서드를 비동기 메서드라고 합니다.

비고

AsyncAwait 키워드는 Visual Studio 2012에서 도입되었습니다. 비동기 프로그래밍에 대한 소개는 Async 및 Await를 사용한 비동기 프로그래밍을 참조하세요.

일반적으로 연산자를 적용 Await 하는 작업은 Task-Based 비동기 패턴( 즉, a 또는 aTask<TResult>)을 구현하는 메서드에 대한 호출의 Task 반환 값입니다.

다음 코드에서 메서드 GetByteArrayAsyncgetContentsTaskHttpClient .Task(Of Byte()) 작업이 완료되면 실제 바이트 배열을 생성할 것을 약속합니다. 연산자는 Await 완료될 때까지 getContentsTask 실행을 SumPageSizesAsync 일시 중단하기 위해 getContentsTask 적용됩니다. 그 동안 컨트롤은 호출자에게 SumPageSizesAsync반환됩니다. getContentsTask 완료되면 식이 Await 바이트 배열로 계산됩니다.

Private Async Function SumPageSizesAsync() As Task

    ' To use the HttpClient type in desktop apps, you must include a using directive and add a
    ' reference for the System.Net.Http namespace.
    Dim client As HttpClient = New HttpClient()
    ' . . .
    Dim getContentsTask As Task(Of Byte()) = client.GetByteArrayAsync(url)
    Dim urlContents As Byte() = Await getContentsTask

    ' Equivalently, now that you see how it works, you can write the same thing in a single line.
    'Dim urlContents As Byte() = Await client.GetByteArrayAsync(url)
    ' . . .
End Function

중요합니다

전체 예제는 연습: Async 및 Await를 사용하여 웹에 액세스하는 것을 참조하세요. .NET 샘플 브라우저에서 샘플을 다운로드할 수 있습니다. 예제 코드는 SerialAsyncExample 프로젝트에 있습니다.

메서드 호출 결과를 반환Task(Of TResult)하는 경우 Await 식의 Await 형식은 TResult입니다. 메서드를 반환Task하는 메서드 호출의 결과에 적용되는 경우 Await 식은 Await 값을 반환하지 않습니다. 다음 예제에서 차이점을 보여 줍니다.

' Await used with a method that returns a Task(Of TResult).
Dim result As TResult = Await AsyncMethodThatReturnsTaskTResult()

' Await used with a method that returns a Task.
Await AsyncMethodThatReturnsTask()

Await 식 또는 문은 실행 중인 스레드를 차단하지 않습니다. 대신 컴파일러가 대기 중인 작업의 연속으로 식 뒤 Await 의 나머지 비동기 메서드를 등록하게 합니다. 그런 다음 컨트롤이 비동기 메서드의 호출자로 돌아갑니다. 작업이 완료되면 해당 연속 작업이 호출되고 비동기 메서드 실행이 중단된 위치에서 다시 시작됩니다.

식은 Await 한정자에 의해 Async 표시된 즉시 바깥쪽 메서드 또는 람다 식의 본문에서만 발생할 수 있습니다. Await라는 용어는 해당 컨텍스트에서만 키워드로 사용됩니다. 다른 곳에서는 식별자로 해석됩니다. Async 메서드 또는 람다 식 Await 내에서는 쿼리 식, Catch Try의 블록에서 Finally 식이 발생할 수 없습니다. 잡기... 마지막으로, or 루프의 For 루프 제어 변수 식 또는 For EachSyncLock 문의 본문에 있는 문입니다.

예외

대부분의 비동기 메서드는 a Task 또는 Task<TResult>. 반환된 작업의 속성은 태스크가 완료되었는지 여부, 비동기 메서드가 예외를 발생시켰는지 또는 취소되었는지 여부 및 최종 결과와 같은 상태 및 기록에 대한 정보를 전달합니다. Await 연산자는 해당 속성에 액세스합니다.

예외를 발생시키는 작업 반환 비동기 메서드를 기다리는 경우 연산자는 Await 예외를 다시 throw합니다.

취소된 Await 작업 반환 비동기 메서드를 기다리는 경우 연산자는 다시 발생합니다 OperationCanceledException.

오류 상태에 있는 단일 작업은 여러 예외를 반영할 수 있습니다. 예를 들어 작업은 Task.WhenAll 호출의 결과일 수 있습니다. 이러한 작업을 기다리는 경우 await 작업은 예외 중 하나만 다시 발생합니다. 그러나 다시 throw되는 예외는 예측할 수 없습니다.

비동기 메서드의 오류 처리 예제는 Try... 잡기... Finally 문입니다.

예시

다음 Windows Forms 예제에서는 비동기 메서드WaitAsynchronouslyAsyncAwait 사용하는 방법을 보여 줍니다. 해당 메서드의 동작과 .의 WaitSynchronously동작을 대조합니다. 연산 WaitSynchronously 자가 Await 없으면 해당 정의에서 한정자를 사용하고 Async 본문에 대한 호출 Thread.Sleep 에도 불구하고 동기적으로 실행됩니다.

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Call the method that runs asynchronously.
    Dim result As String = Await WaitAsynchronouslyAsync()

    ' Call the method that runs synchronously.
    'Dim result As String = Await WaitSynchronously()

    ' Display the result.
    TextBox1.Text &= result
End Sub

' The following method runs asynchronously. The UI thread is not
' blocked during the delay. You can move or resize the Form1 window
' while Task.Delay is running.
Public Async Function WaitAsynchronouslyAsync() As Task(Of String)
    Await Task.Delay(10000)
    Return "Finished"
End Function

' The following method runs synchronously, despite the use of Async.
' You cannot move or resize the Form1 window while Thread.Sleep
' is running because the UI thread is blocked.
Public Async Function WaitSynchronously() As Task(Of String)
    ' Import System.Threading for the Sleep method.
    Thread.Sleep(10000)
    Return "Finished"
End Function

참고하십시오