Async
한정자는 수정하는 메서드 또는 람다 식이 비동기임을 나타냅니다. 이러한 메서드를 비동기 메서드라고 합니다.
비동기 메서드는 호출자의 스레드를 차단하지 않고 장기 실행 작업을 수행하는 편리한 방법을 제공합니다. 비동기 메서드의 호출자는 비동기 메서드가 완료되기를 기다리지 않고 작업을 다시 시작할 수 있습니다.
비고
및 Async
Await
키워드는 Visual Studio 2012에서 도입되었습니다. 비동기 프로그래밍에 대한 소개는 Async 및 Await를 사용한 비동기 프로그래밍을 참조하세요.
다음 예제에서는 비동기 메서드의 구조를 보여줍니다. 규칙에 따라 비동기 메서드 이름은 "Async"로 끝납니다.
Public Async Function ExampleMethodAsync() As Task(Of Integer)
' . . .
' At the Await expression, execution in this method is suspended and,
' if AwaitedProcessAsync has not already finished, control returns
' to the caller of ExampleMethodAsync. When the awaited task is
' completed, this method resumes execution.
Dim exampleInt As Integer = Await AwaitedProcessAsync()
' . . .
' The return statement completes the task. Any method that is
' awaiting ExampleMethodAsync can now get the integer result.
Return exampleInt
End Function
일반적으로 키워드에 의해 Async
수정된 메서드에는 하나 이상의 Await 식 또는 문이 포함됩니다. 메서드는 첫 번째 Await
에 도달할 때까지 동기적으로 실행되며 대기 중인 작업이 완료될 때까지 일시 중단됩니다. 그 동안 컨트롤은 메서드의 호출자에게 반환됩니다. 메서드에 식이나 문이 없 Await
으면 메서드가 일시 중단되지 않고 동기 메서드처럼 실행됩니다. 컴파일러 경고는 해당 상황이 오류를 나타낼 수 있기 때문에 포함되지 Await
않은 비동기 메서드에 대해 경고합니다. 자세한 내용은 컴파일러 오류를 참조하세요.
키 Async
워드는 예약되지 않은 키워드입니다. 메서드 또는 람다 식을 수정할 때 키워드입니다. 다른 모든 컨텍스트에서는 식별자로 해석됩니다.
반환 형식
비동기 메서드는 하위 프로시저 또는 반환 형식 Task 이 있는 함수 프로시저 또는 Task<TResult>. 메서드는 ByRef 매개 변수를 선언할 수 없습니다.
메서드의 Return 문에 TResult 형식의 피연산자를 사용하는 경우 비동기 메서드의 반환 형식을 지정 Task(Of TResult)
합니다. 메서드가 완료되었을 때 의미 있는 값이 반환되지 않을 경우 Task
를 사용합니다. 즉, 메서드에 대한 호출은 반환Task
되지만 Task
완료되면 대기 중인 Task
모든 Await
문이 결과 값을 생성하지 않습니다.
비동기 서브루틴은 프로시저가 필요한 이벤트 처리기를 Sub
정의하는 데 주로 사용됩니다. 비동기 서브루틴의 호출자는 대기할 수 없으며 메서드가 throw하는 예외를 catch할 수 없습니다.
자세한 내용과 예제는 비동기 반환 형식을 참조하세요.
예시
다음 예제에서는 비동기 이벤트 처리기, 비동기 람다 식 및 비동기 메서드를 보여 줍니다. 이러한 요소를 사용하는 전체 예제는 연습: Async 및 Await를 사용하여 웹에 액세스하는 것을 참조하세요. .NET 샘플 브라우저에서 샘플을 다운로드할 수 있습니다. 예제 코드는 SerialAsyncExample 프로젝트에 있습니다.
' An event handler must be a Sub procedure.
Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click
textBox1.Clear()
' SumPageSizesAsync is a method that returns a Task.
Await SumPageSizesAsync()
textBox1.Text = vbCrLf & "Control returned to button1_Click."
End Sub
' The following async lambda expression creates an equivalent anonymous
' event handler.
AddHandler button1.Click, Async Sub(sender, e)
textBox1.Clear()
' SumPageSizesAsync is a method that returns a Task.
Await SumPageSizesAsync()
textBox1.Text = vbCrLf & "Control returned to button1_Click."
End Sub
' The following async method returns a Task(Of T).
' A typical call awaits the Byte array result:
' Dim result As Byte() = Await GetURLContents("https://msdn.com")
Private Async Function GetURLContentsAsync(url As String) As Task(Of Byte())
' The downloaded resource ends up in the variable named content.
Dim content = New MemoryStream()
' Initialize an HttpWebRequest for the current URL.
Dim webReq = CType(WebRequest.Create(url), HttpWebRequest)
' Send the request to the Internet resource and wait for
' the response.
Using response As WebResponse = Await webReq.GetResponseAsync()
' Get the data stream that is associated with the specified URL.
Using responseStream As Stream = response.GetResponseStream()
' Read the bytes in responseStream and copy them to content.
' CopyToAsync returns a Task, not a Task<T>.
Await responseStream.CopyToAsync(content)
End Using
End Using
' Return the result as a byte array.
Return content.ToArray()
End Function
참고하십시오
.NET