如果您不想等待異步應用程式完成,您可以設定按鈕,以用來取消異步應用程式。 依照本主題中的範例,您可以將取消按鈕新增至下載一個網站或網站清單的應用程式。
這些範例會使用 Fine-Tuning "您的異步應用程式" (Visual Basic) 中所描述的 UI。
備註
若要執行範例,您必須在計算機上安裝Visual Studio 2012或更新版本和 .NET Framework 4.5 或更新版本。
取消工作
第一個範例會將 [取消] 按鈕與單一下載工作產生關聯。 如果您在應用程式下載內容時選擇按鈕,則會取消下載。
下載範例
您可以從 異步範例:微調您的應用程式 ,然後遵循下列步驟,下載完整的 Windows Presentation Foundation (WPF) 專案。
解壓縮您下載的檔案,然後啟動 Visual Studio。
在功能表欄上,選擇 [ 檔案]、[ 開啟]、[ 專案/方案]。
在 [ 開啟專案 ] 對話框中,開啟保存解壓縮範例程式代碼的資料夾,然後開啟 AsyncFineTuningVB 的解決方案 (.sln) 檔案。
在 [方案總管] 中,開啟 CancelATask 專案的快捷方式功能表,然後選擇 [ 設定為啟始專案]。
選擇 F5 鍵以執行專案。
選擇 Ctrl+F5 鍵來執行專案,而不進行偵錯。
如果您不想下載專案,您可以在本主題結尾檢閱MainWindow.xaml.vb檔案。
建構範例
下列變更會將 [ 取消] 按鈕新增至下載網站的應用程式。 如果您不想下載或建置範例程式碼,您可以在本主題結尾的「完整範例」部分查看最終產品。 星號會標示程式代碼中的變更。
若要自行建置範例,請逐步遵循「下載範例」一節中的指示,但選擇 StarterCode 作為 StartUp 專案 ,而不是 CancelATask。
然後將下列變更新增至該專案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 實例與每個工作產生關聯,來擴充上一個範例來取消許多工作。 如果您選擇 [ 取消] 按鈕,則會取消尚未完成的所有工作。
下載範例
您可以從 異步範例:微調您的應用程式 ,然後遵循下列步驟,下載完整的 Windows Presentation Foundation (WPF) 專案。
解壓縮您下載的檔案,然後啟動 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.