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.
Il Async
modificatore indica che il metodo o l'espressione lambda che modifica è asincrona. Tali metodi sono definiti metodi asincroni.
Un metodo asincrono offre un modo pratico per eseguire operazioni potenzialmente a esecuzione prolungata senza bloccare il thread del chiamante. Il chiamante di un metodo asincrono può riprendere il lavoro senza attendere il completamento del metodo asincrono.
Annotazioni
Le Async
parole chiave e Await
sono state introdotte in Visual Studio 2012. Per un'introduzione alla programmazione asincrona, vedere Programmazione asincrona con Async e Await.
Nell'esempio seguente viene illustrata la struttura di un metodo asincrono. Per convenzione, i nomi dei metodi asincroni terminano in "Async".
Public Async Function ExampleMethodAsync() As Task(Of Integer)
' . . .
' At the Await expression, execution in this method is suspended and,
' if AwaitedProcessAsync has not already finished, control returns
' to the caller of ExampleMethodAsync. When the awaited task is
' completed, this method resumes execution.
Dim exampleInt As Integer = Await AwaitedProcessAsync()
' . . .
' The return statement completes the task. Any method that is
' awaiting ExampleMethodAsync can now get the integer result.
Return exampleInt
End Function
In genere, un metodo modificato dalla Async
parola chiave contiene almeno un'espressione o un'istruzione Await . Il metodo viene eseguito in modo sincrono fino a raggiungere il primo Await
, a quel punto sospende fino al completamento dell'attività attesa. Nel frattempo, il controllo viene restituito al chiamante del metodo . Se il metodo non contiene un'espressione o un'istruzione Await
, il metodo non viene sospeso ed eseguito come metodo sincrono. Un avviso del compilatore avvisa gli utenti a qualsiasi metodo asincrono che non contiene Await
perché tale situazione potrebbe indicare un errore. Per altre informazioni, vedere l'errore del compilatore.
La Async
parola chiave è una parola chiave non valida. Si tratta di una parola chiave quando modifica un metodo o un'espressione lambda. In tutti gli altri contesti, viene interpretato come identificatore.
Tipi restituiti
Un metodo asincrono è una routine Sub o una routine Function con un tipo restituito di Task o Task<TResult>. Il metodo non può dichiarare parametri ByRef .
Specificare Task(Of TResult)
per il tipo restituito di un metodo asincrono se l'istruzione Return del metodo ha un operando di tipo TResult. Utilizzare Task
se non viene restituito alcun valore significativo al completamento del metodo. Ovvero, una chiamata al metodo restituisce un Task
oggetto , ma quando l'oggetto Task
viene completato, qualsiasi Await
istruzione in attesa Task
di non produce un valore di risultato.
Le subroutine asincrone vengono usate principalmente per definire i gestori eventi in cui è necessaria una Sub
routine. Il chiamante di una subroutine asincrona non può attenderlo e non può intercettare le eccezioni generate dal metodo.
Per altre informazioni ed esempi, vedere Tipi restituiti asincroni.
Esempio
Gli esempi seguenti illustrano un gestore eventi asincrono, un'espressione lambda asincrona e un metodo asincrono. Per un esempio completo che usa questi elementi, vedere Procedura dettagliata: Accesso al Web tramite Async e Await. È possibile scaricare l'esempio dal browser di esempio .NET. Il codice di esempio si trova nel progetto SerialAsyncExample.
' An event handler must be a Sub procedure.
Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click
textBox1.Clear()
' SumPageSizesAsync is a method that returns a Task.
Await SumPageSizesAsync()
textBox1.Text = vbCrLf & "Control returned to button1_Click."
End Sub
' The following async lambda expression creates an equivalent anonymous
' event handler.
AddHandler button1.Click, Async Sub(sender, e)
textBox1.Clear()
' SumPageSizesAsync is a method that returns a Task.
Await SumPageSizesAsync()
textBox1.Text = vbCrLf & "Control returned to button1_Click."
End Sub
' The following async method returns a Task(Of T).
' A typical call awaits the Byte array result:
' Dim result As Byte() = Await GetURLContents("https://msdn.com")
Private Async Function GetURLContentsAsync(url As String) As Task(Of Byte())
' The downloaded resource ends up in the variable named content.
Dim content = New MemoryStream()
' Initialize an HttpWebRequest for the current URL.
Dim webReq = CType(WebRequest.Create(url), HttpWebRequest)
' Send the request to the Internet resource and wait for
' the response.
Using response As WebResponse = Await webReq.GetResponseAsync()
' Get the data stream that is associated with the specified URL.
Using responseStream As Stream = response.GetResponseStream()
' Read the bytes in responseStream and copy them to content.
' CopyToAsync returns a Task, not a Task<T>.
Await responseStream.CopyToAsync(content)
End Using
End Using
' Return the result as a byte array.
Return content.ToArray()
End Function