Condividi tramite


Async (Visual Basic)

Il modificatore Async indica che il metodo o l'espressione lambda che l'ha modificato è asincrono. Tali metodi vengono definiti metodi async.

Un metodo async consente di eseguire senza problemi 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 async.

Nota

Le parole chiave Await e Async introdotte in Visual Studio 2012.Per un'introduzione alla programmazione asincrona, vedere Programmazione asincrona con Async e Await (C# e Visual Basic).

Nell'esempio seguente viene mostrata 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, in quel punto si sospende finché l'attività attesa non viene completata. Nel frattempo, il controllo viene ritornato 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. Avviso del compilatore che segnala di eventuali metodi async 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 async è una routine Sub, o una routine Function che ha un tipo di ritorno Task oppure Task. Il metodo non può dichiarare nessun parametro 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 quando il metodo termina. Ovvero una chiamata al metodo restituisce Task, ma quando il Task viene completato, ogni istruzione Await in attesa di Task non produce un valore risultato.

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

Per ulteriori informazioni ed esempi, vedere Tipi restituiti asincroni (C# e Visual Basic).

Esempio

Negli esempi seguenti viene illustrato un gestore eventi async, un'espressione lambda async e un metodo async. Per un esempio completo che utilizza questi elementi, vedere Procedura dettagliata: accesso al Web tramite Async e Await (C# e Visual Basic). È possibile scaricare il codice della procedura dettagliata dalla pagina degli esempi di codice per gli sviluppatori.

' 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

Vedere anche

Attività

Procedura dettagliata: accesso al Web tramite Async e Await (C# e Visual Basic)

Riferimenti

Opertore Await (Visual Basic)

AsyncStateMachineAttribute

Concetti

Programmazione asincrona con Async e Await (C# e Visual Basic)