Async (Visual Basic)

Il modificatore Async indica che il metodo o l'espressione lambda che modifica sono asincroni. Tali metodi vengono definiti metodi Async.

Un metodo asincrono è un modo pratico per eseguire le operazioni potenzialmente di lunga durata senza bloccare il thread del chiamante. Il chiamante di un metodo Async può riprendere un'operazione senza attendere la fine del metodo asincrono.

Nota

Le parole chiave Async 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 async. Per convenzione, i nomi dei metodi async terminano con "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 parola chiave Async contiene almeno un'espressione o un'istruzione Await. Il metodo funziona in modo sincrono fino al primo Await, a quel punto viene sospeso finché l'attività di cui si è in attesa non viene completata. 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 e viene eseguito come un metodo sincrono. Un avviso del compilatore segnala eventuali metodi asincroni che non contengono Await perché questa situazione potrebbe indicare un errore. Per ulteriori informazioni, vedere gli errori di compilazione.

La parola chiave Async è una parola chiave non riservata. È una parola chiave quando si modifica un metodo o un'espressione lambda. In tutti gli altri contesti, viene interpretata come identificatore.

Tipi restituiti

Un metodo asincrono è una routine Sub o una routine Function con tipo restituito Task o Task<TResult>. Il metodo non può dichiarare parametri ByRef.

Specificare Task(Of TResult) come tipo restituito del metodo Async 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. In altre parole, una chiamata al metodo restituisce Task, ma quando Task viene completato, ogni istruzione Await in attesa di Task non produce un valore risultante.

Le subroutine async vengono utilizzate principalmente per definire i gestori eventi in cui è richiesta una procedura Sub. Il chiamante di una subroutine async non può attendere il metodo e non può intercettare le eccezioni generate dal metodo.

Per altre informazioni ed esempi, vedere Tipi restituiti asincroni.

Esempio

Negli esempi seguenti viene illustrato un gestore eventi async, un'espressione lambda async e un metodo async. Per un esempio completo che usa tali 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

Vedi anche