Share via


Async (Visual Basic)

Il modificatore di Async indica che il metodo o espressione lambda che modifica è asincrono.Tali metodi sono definiti i metodi async.

Un metodo async fornisce un modo pratico per eseguire il lavoro potenzialmente prolungata senza bloccare il thread del chiamante.Il chiamante di un metodo async può riattivare il proprio lavoro senza attendere il metodo async per completare.

[!NOTA]

Le parole chiave di Await e di Async furono introdotte in Visual Studio 2012.Per informazioni sulle nuove funzionalità della versione, vedere Novità di Visual Studio 2012.

Per un'introduzione alla programmazione async, 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 del metodo async 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 parola chiave di Async contiene almeno un un'espressione o istruzione di Attendere.Il metodo funziona in modo sincrono finché non raggiungerà primo Await, al momento sospende finché l'attività attesa non completi.Contemporaneamente, il controllo viene restituito al chiamante del metodo.Se il metodo non contiene un'espressione o un'istruzione di Await, il metodo non viene sospeso e non esegue come un metodo sincrono su.Un avviso del compilatore segnala gli eventuali metodi async che non contengono Await perché tale situazione potrebbe indicare un errore.Per ulteriori informazioni, vedere errore del compilatore.

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

Tipi restituiti

Un metodo asincrono viene una routine di In, una routine o di Funzione con un tipo restituito di Task o di Task<TResult>.Il metodo non può dichiarare parametri di ByRef.

Specificare Task(Of TResult) per il tipo restituito del metodo async se l'istruzione di Ritorno del metodo dispone di un operando di tipo TResult.Se si utilizza Task alcun valore significativo viene restituito quando il metodo viene completato.Ovvero una chiamata al metodo restituisce Task, ma quando Task viene completata, qualsiasi istruzione di Await in attesa di Task non produce un valore.

Le subroutine di Asincrone vengono utilizzate principalmente per definire i gestori eventi in cui una routine di Sub è necessaria.Il chiamante di una subroutine async non è possibile attenderlo e non può intercettare le eccezioni che il metodo genera un'eccezione.

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 da Esempi di codice dello sviluppatore.

' 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)