如果您不想等待操作完成,可以在一段时间后使用CancellationTokenSource.CancelAfter方法来取消异步操作。 此方法计划取消表达式指定的 CancelAfter
时间段内未完成的任何关联任务。
本示例将添加到 “取消异步任务”或“任务列表”(Visual Basic) 中开发的代码,以下载网站列表并显示每个网站内容的长度。
注释
若要运行示例,必须在计算机上安装 Visual Studio 2012 或更高版本和 .NET Framework 4.5 或更高版本。
下载示例
可以从异步示例下载完整的 Windows Presentation Foundation (WPF) 项目 :微调应用程序 ,然后执行以下步骤。
解压缩下载的文件,然后启动 Visual Studio。
在菜单栏上,选择 “文件”、“ 打开”、“ 项目/解决方案”。
在 “打开项目 ”对话框中,打开保存解压缩的示例代码的文件夹,然后打开 AsyncFineTuningVB 的解决方案(.sln)文件。
在 解决方案资源管理器中,打开 CancelAfterTime 项目的快捷菜单,然后选择 “设置为启动项目”。
选择要运行项目的 F5 键。
选择 Ctrl+F5 键以运行项目而不对其进行调试。
多次运行程序以验证输出是否显示所有网站的输出、不显示网站的输出或显示某些网站的输出。
如果不想下载项目,可以在本主题末尾查看MainWindow.xaml.vb文件。
生成示例
本主题中的示例将添加到在 “取消异步任务”或“任务列表”(Visual Basic) 中开发的项目,以取消任务列表。 该示例使用相同的 UI,尽管未显式使用 “取消” 按钮。
若要自行构建示例,请逐步按照“下载示例”部分中的说明进行操作,但选择 CancelAListOfTasks 作为 启动项目。 将本主题中的更改添加到该项目。
若要在任务被标记为已取消之前指定最长时限,请按照以下示例添加对CancelAfter
至startButton_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.