Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
È possibile annullare un'operazione asincrona dopo un periodo di tempo usando il CancellationTokenSource.CancelAfter metodo se non si vuole attendere il completamento dell'operazione. Questo metodo pianifica l'annullamento di tutte le attività associate che non vengono completate entro il periodo di tempo designato dall'espressione CancelAfter .
In questo esempio viene aggiunto al codice sviluppato in Annulla un'attività asincrona o un elenco di attività (Visual Basic) per scaricare un elenco di siti Web e visualizzare la lunghezza del contenuto di ognuno di essi.
Annotazioni
Per eseguire gli esempi, è necessario che Nel computer sia installato Visual Studio 2012 o versione successiva e .NET Framework 4.5 o versione successiva.
Download dell'esempio
È possibile scaricare il progetto Windows Presentation Foundation (WPF) completo da Esempio asincrono: Ottimizzazione dell'applicazione e quindi seguire questa procedura.
Decomprimere il file scaricato e quindi avviare Visual Studio.
Sulla barra dei menu scegliere File, Apri, Progetto/Soluzione.
Nella finestra di dialogo Apri progetto aprire la cartella contenente il codice di esempio decompresso e quindi aprire il file della soluzione (.sln) per AsyncFineTuningVB.
In Esplora soluzioni aprire il menu di scelta rapida per il progetto CancelAfterTime e quindi scegliere Imposta come progetto di avvio.
Scegliere il tasto F5 per eseguire il progetto.
Scegliere i tasti CTRL+F5 per eseguire il progetto senza eseguirne il debug.
Eseguire il programma più volte per verificare che l'output potrebbe mostrare risultati per tutti, nessuno o alcuni siti web.
Se non si vuole scaricare il progetto, è possibile esaminare il file di MainWindow.xaml.vb alla fine di questo argomento.
Compilazione dell'esempio
Nell'esempio in questo argomento, viene ampliato il progetto sviluppato in Annulla un'attività asincrona o un elenco di attività (Visual Basic) per consentire l'annullamento di un elenco di attività. L'esempio usa la stessa interfaccia utente, anche se il pulsante Annulla non viene usato in modo esplicito.
Per costruire passo passo l'esempio da soli, seguire le istruzioni nella sezione "Scaricamento dell'Esempio", ma scegliere CancelAListOfTasks come progetto di avvio. Aggiungi le modifiche di questo argomento a quel progetto.
Per specificare un tempo massimo prima che le attività vengano contrassegnate come annullate, aggiungere una chiamata a CancelAfterstartButton_Click, come illustrato nell'esempio seguente. L'addizione è contrassegnata con asterischi.
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
Eseguire il programma più volte per verificare che l'output potrebbe mostrare risultati per tutti, nessuno o alcuni siti web. L'output seguente è un esempio:
Length of the downloaded string: 35990.
Length of the downloaded string: 407399.
Length of the downloaded string: 226091.
Downloads canceled.
Esempio completo
Il codice seguente è il testo completo del file MainWindow.xaml.vb per l'esempio. Gli asterischi contrassegnano gli elementi aggiunti per questo esempio.
Si noti che è necessario aggiungere un riferimento per System.Net.Http.
È possibile scaricare il progetto da Esempio asincrono: Ottimizzazione dell'applicazione.
' 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.
Vedere anche
- Programmazione asincrona con Async e Await (Visual Basic)
- Procedura dettagliata: Accesso al Web tramite Async e Await (Visual Basic)
- Annullare un'attività asincrona o un elenco di attività (Visual Basic)
- Fine-Tuning La Tua Applicazione Asincrona (Visual Basic)
- Esempio asincrono: Ottimizzazione dell'applicazione