共用方式為


在一段時間後取消異步任務(Visual Basic)

如果您不想等待作業完成,您可以在一段時間後使用CancellationTokenSource.CancelAfter 方法來取消該異步作業。 此方法會排程取消在由 CancelAfter 表達式指定的時間段內未完成的任何相關任務。

本範例擴充基於 取消異步工作或工作清單 (Visual Basic) 的程序代碼,以下載網站清單並顯示每個網站內容的長度。

備註

若要執行範例,您必須在計算機上安裝Visual Studio 2012或更新版本和 .NET Framework 4.5 或更新版本。

下載範例

您可以從 異步範例:微調您的應用程式 ,然後遵循下列步驟,下載完整的 Windows Presentation Foundation (WPF) 專案。

  1. 解壓縮您下載的檔案,然後啟動 Visual Studio。

  2. 在功能表欄上,選擇 [ 檔案]、[ 開啟]、[ 專案/方案]。

  3. 在 [ 開啟專案 ] 對話框中,開啟保存解壓縮範例程式代碼的資料夾,然後開啟 AsyncFineTuningVB 的解決方案 (.sln) 檔案。

  4. [方案總管] 中,開啟 CancelAfterTime 專案的快捷方式功能表,然後選擇 [ 設定為啟始專案]。

  5. 選擇 F5 鍵以執行專案。

    選擇 Ctrl+F5 鍵來執行專案,而不進行偵錯。

  6. 執行程式數次,以確認輸出的變化情況,可能會顯示所有網站的資料、沒有網站的資料或某些網站的資料。

如果您不想下載專案,您可以在本主題結尾檢閱MainWindow.xaml.vb檔案。

建構範例

本主題中的範例增加了在 取消異步工作或工作清單 (Visual Basic) 中開發的專案,以便取消工作清單。 雖然未明確使用 [取消 ] 按鈕,但此範例會使用相同的UI。

若要自行建置範例,請逐步遵循「下載範例」一節中的指示,但選擇 CancelAListOfTasks 作為 StartUp 專案。 將本主題中的變更新增至該專案。

若要指定工作標示為取消之前的最大時間,請新增 對 CancelAfterstartButton_Click的呼叫,如下列範例所示。 新增項目以星號標記。

Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)

    ' Instantiate the CancellationTokenSource.
    cts = New CancellationTokenSource()

    resultsTextBox.Clear()

    Try
        ' ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
        ' can adjust the time.)
        cts.CancelAfter(2500)

        Await AccessTheWebAsync(cts.Token)
        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

執行程式數次,以確認輸出的變化情況,可能會顯示所有網站的資料、沒有網站的資料或某些網站的資料。 下列輸出是範例:

Length of the downloaded string: 35990.

Length of the downloaded string: 407399.

Length of the downloaded string: 226091.

Downloads canceled.

完整範例

下列程式代碼是範例中MainWindow.xaml.vb檔案的完整文字。 星號標記的是為此範例新增的元素。

請注意,您必須新增System.Net.Http的引用。

您可以從 異步範例:微調應用程式下載專案。

' 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
            ' ***Set up the CancellationTokenSource to cancel after 2.5 seconds. (You
            ' can adjust the time.)
            cts.CancelAfter(2500)

            Await AccessTheWebAsync(cts.Token)
            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

    ' You can still include a Cancel button if you want to.
    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()

        ' Process each element in 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

' Sample output:

' Length of the downloaded string: 35990.

' Length of the downloaded string: 407399.

' Length of the downloaded string: 226091.

' Downloads canceled.

另請參閱