완료되기를 기다리지 않으려는 경우 비동기 애플리케이션을 취소하는 데 사용할 수 있는 단추를 설정할 수 있습니다. 이 항목의 예제에 따라 하나의 웹 사이트 또는 웹 사이트 목록을 다운로드하는 취소 단추를 애플리케이션에 추가할 수 있습니다.
Fine-Tuning 비동기 애플리케이션(Visual Basic)에서 설명하는 UI를 예제에서 사용합니다.
비고
예제를 실행하려면 Visual Studio 2012 이상과 .NET Framework 4.5 이상이 컴퓨터에 설치되어 있어야 합니다.
작업 취소
첫 번째 예제에서는 취소 단추를 단일 다운로드 작업에 연결합니다. 애플리케이션에서 콘텐츠를 다운로드하는 동안 단추를 선택하면 다운로드가 취소됩니다.
예제 다운로드
비동기 샘플: 애플리케이션 미세 조정에서 전체 WPF(Windows Presentation Foundation) 프로젝트를 다운로드한 다음 다음 단계를 수행할 수 있습니다.
다운로드한 파일의 압축을 해제한 다음 Visual Studio를 시작합니다.
메뉴 모음에서 파일, 열기, 프로젝트/솔루션을 선택합니다.
프로젝트 열기 대화 상자에서 압축을 푼 샘플 코드가 들어 있는 폴더를 연 다음 AsyncFineTuningVB에 대한 솔루션(.sln) 파일을 엽니다.
솔루션 탐색기에서 CancelATask 프로젝트의 바로 가기 메뉴를 열고 시작 프로젝트로 설정을 선택합니다.
F5 키를 선택하여 프로젝트를 실행합니다.
프로젝트를 디버깅하지 않고 실행하려면 Ctrl+F5 키를 선택합니다.
프로젝트를 다운로드하지 않으려면 이 항목의 끝에 MainWindow.xaml.vb 파일을 검토할 수 있습니다.
예제를 구축하기
다음 변경 내용은 웹 사이트를 다운로드하는 애플리케이션에 취소 단추를 추가합니다. 예제를 다운로드하거나 빌드하지 않으려면 이 항목의 끝에 있는 "전체 예제" 섹션에서 최종 제품을 검토할 수 있습니다. 별표는 코드의 변경 내용을 표시합니다.
예제를 직접 빌드하려면 단계별로 "예제 다운로드" 섹션의 지침을 따르지만 CancelATask 대신 시작 프로젝트로 StarterCode를 선택합니다.
그런 다음, 해당 프로젝트의 MainWindow.xaml.vb 파일에 다음 변경 내용을 추가합니다.
CancellationTokenSource
변수에 액세스하는 모든 메서드의 범위 내에서 사용할 수 있도록 변수cts
를 선언합니다.Class MainWindow ' ***Declare a System.Threading.CancellationTokenSource. Dim cts As CancellationTokenSource
취소 단추에 대해 다음 이벤트 처리기를 추가합니다. 이벤트 처리기는 CancellationTokenSource.Cancel 메서드를 사용하여 사용자가 취소를 요청할 때
cts
에게 알립니다.' ***Add an event handler for the Cancel button. Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs) If cts IsNot Nothing Then cts.Cancel() End If End Sub
시작 단추
startButton_Click
에 대한 이벤트 처리기에서 다음과 같이 변경합니다.CancellationTokenSource
와cts
을 인스턴스화합니다.' ***Instantiate the CancellationTokenSource. cts = New CancellationTokenSource()
지정된 웹 사이트의 콘텐츠를 다운로드하는
AccessTheWebAsync
호출에서 CancellationTokenSource.Token의cts
속성을 인수로 보냅니다.Token
취소가 요청되면 속성이 메시지를 전파합니다. 사용자가 다운로드 작업을 취소하도록 선택하는 경우 메시지를 표시하는 catch 블록을 추가합니다. 다음 코드는 변경 내용을 보여줍니다.Try ' ***Send a token to carry the message if cancellation is requested. Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token) resultsTextBox.Text &= vbCrLf & $"Length of the downloaded string: {contentLength}." & vbCrLf ' *** If cancellation is requested, an OperationCanceledException results. Catch ex As OperationCanceledException resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf Catch ex As Exception resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf End Try
AccessTheWebAsync
에서 HttpClient.GetAsync(String, CancellationToken) 형식의GetAsync
메서드의 HttpClient 오버로드를 사용하여 웹 사이트의 콘텐츠를 다운로드합니다.ct
의 매개 변수인 CancellationToken을 두 번째 인수로AccessTheWebAsync
에 전달합니다. 사용자가 취소 단추를 선택하면 토큰이 메시지를 전달합니다.다음 코드는 .의
AccessTheWebAsync
변경 내용을 보여줍니다.' ***Provide a parameter for the CancellationToken. Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer) Dim client As HttpClient = New HttpClient() resultsTextBox.Text &= vbCrLf & "Ready to download." & vbCrLf ' You might need to slow things down to have a chance to cancel. Await Task.Delay(250) ' GetAsync returns a Task(Of HttpResponseMessage). ' ***The ct argument carries the message if the Cancel button is chosen. Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/library/dd470362.aspx", ct) ' Retrieve the website contents from the HttpResponseMessage. Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync() ' The result of the method is the length of the downloaded website. Return urlContents.Length End Function
프로그램을 취소하지 않으면 다음 출력이 생성됩니다.
Ready to download. Length of the downloaded string: 158125.
프로그램이 콘텐츠 다운로드를 완료하기 전에 취소 단추를 선택하면 프로그램에서 다음 출력을 생성합니다.
Ready to download. Download canceled.
작업 목록 취소
이전 예제를 확장하여 동일한 CancellationTokenSource
인스턴스를 각 태스크와 연결하여 많은 작업을 취소할 수 있습니다.
취소 단추를 선택하면 아직 완료되지 않은 모든 작업을 취소합니다.
예제 다운로드
비동기 샘플: 애플리케이션 미세 조정에서 전체 WPF(Windows Presentation Foundation) 프로젝트를 다운로드한 다음 다음 단계를 수행할 수 있습니다.
다운로드한 파일의 압축을 해제한 다음 Visual Studio를 시작합니다.
메뉴 모음에서 파일, 열기, 프로젝트/솔루션을 선택합니다.
프로젝트 열기 대화 상자에서 압축을 푼 샘플 코드가 들어 있는 폴더를 연 다음 AsyncFineTuningVB에 대한 솔루션(.sln) 파일을 엽니다.
솔루션 탐색기에서 CancelAListOfTasks 프로젝트의 바로 가기 메뉴를 열고 시작 프로젝트로 설정을 선택합니다.
F5 키를 선택하여 프로젝트를 실행합니다.
프로젝트를 디버깅하지 않고 실행하려면 Ctrl+F5 키를 선택합니다.
프로젝트를 다운로드하지 않으려면 이 항목의 끝에 MainWindow.xaml.vb 파일을 검토할 수 있습니다.
예제를 구축하기
예제를 직접 확장하려면 단계별로 "예제 다운로드" 섹션의 지침에 따라 시작 프로젝트로 CancelATask를 선택합니다. 해당 프로젝트에 다음 변경 내용을 추가합니다. 별표는 프로그램의 변경 내용을 표시합니다.
웹 주소 목록을 만드는 메서드를 추가합니다.
' ***Add a method that creates a list of web addresses. Private Function SetUpURLList() As List(Of String) Dim urls = New List(Of String) From { "https://msdn.microsoft.com", "https://msdn.microsoft.com/library/hh290138.aspx", "https://msdn.microsoft.com/library/hh290140.aspx", "https://msdn.microsoft.com/library/dd470362.aspx", "https://msdn.microsoft.com/library/aa578028.aspx", "https://msdn.microsoft.com/library/ms404677.aspx", "https://msdn.microsoft.com/library/ff730837.aspx" } Return urls End Function
에서 메서드를 호출합니다
AccessTheWebAsync
.' ***Call SetUpURLList to make a list of web addresses. Dim urlList As List(Of String) = SetUpURLList()
다음 루프를
AccessTheWebAsync
추가하여 목록의 각 웹 주소를 처리합니다.' ***Add a loop to process the list of web addresses. For Each url In urlList ' GetAsync returns a Task(Of HttpResponseMessage). ' Argument ct carries the message if the Cancel button is chosen. ' ***Note that the Cancel button can cancel all remaining downloads. Dim response As HttpResponseMessage = Await client.GetAsync(url, ct) ' Retrieve the website contents from the HttpResponseMessage. Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync() resultsTextBox.Text &= vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf Next
길이가 표시되므로
AccessTheWebAsync
메서드는 아무 것도 반환할 필요가 없습니다. return 문을 제거하고 메서드의 반환 형식을 대신 . Task 로 Task<TResult>변경합니다.Async Function AccessTheWebAsync(ct As CancellationToken) As Task
식 대신 문을 사용하여 메서드
startButton_Click
를 호출합니다.Await AccessTheWebAsync(cts.Token)
프로그램을 취소하지 않으면 다음 출력이 생성됩니다.
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Length of the downloaded string: 158124. Length of the downloaded string: 204890. Length of the downloaded string: 175488. Length of the downloaded string: 145790. Downloads complete.
다운로드가 완료되기 전에 취소 단추를 선택하면 출력에 취소 전에 완료된 다운로드 길이가 포함됩니다.
Length of the downloaded string: 35939. Length of the downloaded string: 237682. Length of the downloaded string: 128607. Downloads canceled.
전체 예제
다음 섹션에는 이전 예제 각각에 대한 코드가 포함되어 있습니다. System.Net.Http에 대한 참조를 추가해야 함을 알아두세요.
비동기 샘플: 애플리케이션 미세 조정에서 프로젝트를 다운로드할 수 있습니다.
작업 취소 예제
다음 코드는 단일 작업을 취소하는 예제의 전체 MainWindow.xaml.vb 파일입니다.
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' ***Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' ***Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
' ***Send a token to carry the message if cancellation is requested.
Dim contentLength As Integer = Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &=
vbCrLf & $"Length of the downloaded string: {contentLength}." & vbCrLf
' *** If cancellation is requested, an OperationCanceledException results.
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf
End Try
' ***Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' ***Add an event handler for the Cancel button.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' ***Provide a parameter for the CancellationToken.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task(Of Integer)
Dim client As HttpClient = New HttpClient()
resultsTextBox.Text &=
vbCrLf & "Ready to download." & vbCrLf
' You might need to slow things down to have a chance to cancel.
Await Task.Delay(250)
' GetAsync returns a Task(Of HttpResponseMessage).
' ***The ct argument carries the message if the Cancel button is chosen.
Dim response As HttpResponseMessage = Await client.GetAsync("https://msdn.microsoft.com/library/dd470362.aspx", ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
' The result of the method is the length of the downloaded website.
Return urlContents.Length
End Function
End Class
' Output for a successful download:
' Ready to download.
' Length of the downloaded string: 158125.
' Or, if you cancel:
' Ready to download.
' Download canceled.
작업 목록 취소 예제
다음 코드는 작업 목록을 취소하는 예제의 전체 MainWindow.xaml.vb 파일입니다.
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
' ***AccessTheWebAsync returns a Task, not a Task(Of Integer).
Await AccessTheWebAsync(cts.Token)
' ***Small change in the display lines.
resultsTextBox.Text &= vbCrLf & "Downloads complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' Add an event handler for the Cancel button.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' ***Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' ***Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' ***Add a loop to process the list of web addresses.
For Each url In urlList
' GetAsync returns a Task(Of HttpResponseMessage).
' Argument ct carries the message if the Cancel button is chosen.
' ***Note that the Cancel button can cancel all remaining downloads.
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
resultsTextBox.Text &=
vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf
Next
End Function
' ***Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/hh290138.aspx",
"https://msdn.microsoft.com/library/hh290140.aspx",
"https://msdn.microsoft.com/library/dd470362.aspx",
"https://msdn.microsoft.com/library/aa578028.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Output if you do not choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Length of the downloaded string: 158124.
' Length of the downloaded string: 204890.
' Length of the downloaded string: 175488.
' Length of the downloaded string: 145790.
' Downloads complete.
' Sample output if you choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Downloads canceled.
참고하십시오
.NET