Como esta chamada não é aguardada, o método atual continua sendo executado antes da chamada ser concluída

Mensagem de erro

Como esta chamada não é aguardada, a execução do método atual continua antes da conclusão da chamada.Considere a aplicação “esperam” operador o resultado de chamada.

O método atual chama um método de async que retorna Task ou Task e não aplique o operador de espere o resultado. A chamada para o método de async inicia uma tarefa assíncrono. Em o entanto, como não operador de Await é aplicado, o programa continua sem esperar que a tarefa termina. Em a maioria dos casos, esse comportamento não é esperado. Geralmente outros aspectos do método de chamada dependem dos resultados da chamada ou, mìnima, o método é chamado esperado complete antes de retornar o método que contém a chamada.

Um problema também importante é o que acontece com exceções que são geradas no método chamado de async. Uma exceção que é lançada em um método que retorna Task ou Task é armazenada na tarefa retornado. Se você não pretende a tarefa ou explicitamente a verificação para exceções, a exceção é perdida. Se você pretende a tarefa, a exceção é rethrown.

Como prática recomendada, você sempre deve esperar a chamada.

Por padrão, este mensagem é um aviso. Para mais informações sobre como ocultar avisos ou tratar avisos como erros, veja Configurando avisos no Visual Basic.

Identificação do erro: BC42358

Para resolver este aviso

  • Você deve considerar suprimir o aviso somente se tiver certeza que você não deseja aguardar que a chamada assíncrona para concluir e que o método chamado não gerará as exceções. Em esse caso, você pode suprimir o aviso atribuir o resultado da tarefa de chamada para uma variável.

    O exemplo a seguir mostra como fazer com que o aviso, como suprimi-lo, e como esperar a chamada.

        Async Function CallingMethodAsync() As Task
    
            ResultsTextBox.Text &= vbCrLf & "  Entering calling method."
    
            ' Variable delay is used to slow down the called method so that you
            ' can distinguish between awaiting and not awaiting in the program's output. 
            ' You can adjust the value to produce the output that this topic shows 
            ' after the code.
            Dim delay = 5000
    
            ' Call #1.
            ' Call an async method. Because you don't await it, its completion isn't 
            ' coordinated with the current method, CallingMethodAsync.
            ' The following line causes the warning.
            CalledMethodAsync(delay)
    
            ' Call #2.
            ' To suppress the warning without awaiting, you can assign the 
            ' returned task to a variable. The assignment doesn't change how
            ' the program runs. However, the recommended practice is always to
            ' await a call to an async method.
            ' Replace Call #1 with the following line.
            'Task delayTask = CalledMethodAsync(delay)
    
            ' Call #3
            ' To contrast with an awaited call, replace the unawaited call 
            ' (Call #1 or Call #2) with the following awaited call. The best 
            ' practice is to await the call.
    
            'Await CalledMethodAsync(delay)
    
            ' If the call to CalledMethodAsync isn't awaited, CallingMethodAsync
            ' continues to run and, in this example, finishes its work and returns
            ' to its caller.
            ResultsTextBox.Text &= vbCrLf & "  Returning from calling method."
        End Function
    
        Async Function CalledMethodAsync(howLong As Integer) As Task
    
            ResultsTextBox.Text &= vbCrLf & "    Entering called method, starting and awaiting Task.Delay."
            ' Slow the process down a little so you can distinguish between awaiting
            ' and not awaiting. Adjust the value for howLong if necessary.
            Await Task.Delay(howLong)
            ResultsTextBox.Text &= vbCrLf & "    Task.Delay is finished--returning from called method."
        End Function
    

    Em o exemplo, se você escolher a chamada nº ou chama origem nº terminar, os unawaited do método de async (CalledMethodAsync) após o chamadorCallingMethodAsync() e o chamador do chamadorStartButton_Click() está concluída. A última linha de saída a seguir mostra quando o método chamado completa. A entrada e a saída do manipulador de eventos que chama CallingMethodAsync no exemplo completo são marcadas na saída.

    Entering the Click event handler.
      Entering calling method.
        Entering called method, starting and awaiting Task.Delay.
      Returning from calling method.
    Exiting the Click event handler.
        Task.Delay is finished--returning from called method.
    

Exemplo

O exemplo a seguir aplicativo Windows Presentation Foundation (WPF) contém os métodos do exemplo anterior. As seguintes etapas para configurar o aplicativo.

  1. Criar um aplicativo WPF, e denomine-o AsyncWarning.

  2. Em o editor de códigos do Visual Studio, escolha a guia de MainWindow.xaml .

    Se a guia não estiver visível, abra o menu de atalho para MainWindow.xaml em Gerenciador de Soluções, e então escolha Exibir Código.

  3. Substitua o código no modo de XAML de MainWindow.xaml com o código a seguir.

    <Window x:Class="MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button x:Name="StartButton" Content="Start" HorizontalAlignment="Left" Margin="214,28,0,0" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Center" FontWeight="Bold" FontFamily="Aharoni" Click="StartButton_Click" />
            <TextBox x:Name="ResultsTextBox" Margin="0,80,0,0" TextWrapping="Wrap" FontFamily="Lucida Console"/>
        </Grid>
    </Window>
    

    Uma janela que contém um botão simples e uma caixa de texto aparece no modo de Design de MainWindow.xaml.

    Para obter mais informações sobre o designer de exibição XAML, consulte Criando uma interface de usuário usando o Designer XAML. Para obter informações sobre como criar seu próprio interface de usuário simples, consulte “para criar um aplicativo WPF” e “criar seções WPF um MainWindow simples” de Instruções passo a passo: acessando a Web e usando Async e Await (C# e Visual Basic).

  4. Substitua o código em MainWindow.xaml.vb com o código a seguir.

    Class MainWindow 
    
        Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
    
            ResultsTextBox.Text &= vbCrLf & "Entering the Click event handler."
            Await CallingMethodAsync()
            ResultsTextBox.Text &= vbCrLf & "Exiting the Click event handler."
        End Sub
    
    
        Async Function CallingMethodAsync() As Task
    
            ResultsTextBox.Text &= vbCrLf & "  Entering calling method."
    
            ' Variable delay is used to slow down the called method so that you
            ' can distinguish between awaiting and not awaiting in the program's output. 
            ' You can adjust the value to produce the output that this topic shows 
            ' after the code.
            Dim delay = 5000
    
            ' Call #1.
            ' Call an async method. Because you don't await it, its completion isn't 
            ' coordinated with the current method, CallingMethodAsync.
            ' The following line causes the warning.
            CalledMethodAsync(delay)
    
            ' Call #2.
            ' To suppress the warning without awaiting, you can assign the 
            ' returned task to a variable. The assignment doesn't change how
            ' the program runs. However, the recommended practice is always to
            ' await a call to an async method.
    
            ' Replace Call #1 with the following line.
            'Task delayTask = CalledMethodAsync(delay)
    
            ' Call #3
            ' To contrast with an awaited call, replace the unawaited call 
            ' (Call #1 or Call #2) with the following awaited call. The best 
            ' practice is to await the call.
    
            'Await CalledMethodAsync(delay)
    
            ' If the call to CalledMethodAsync isn't awaited, CallingMethodAsync
            ' continues to run and, in this example, finishes its work and returns
            ' to its caller.
            ResultsTextBox.Text &= vbCrLf & "  Returning from calling method."
        End Function
    
        Async Function CalledMethodAsync(howLong As Integer) As Task
    
            ResultsTextBox.Text &= vbCrLf & "    Entering called method, starting and awaiting Task.Delay."
            ' Slow the process down a little so you can distinguish between awaiting
            ' and not awaiting. Adjust the value for howLong if necessary.
            Await Task.Delay(howLong)
            ResultsTextBox.Text &= vbCrLf & "    Task.Delay is finished--returning from called method."
        End Function
    
    End Class
    
    ' Output
    
    ' Entering the Click event handler.
    '   Entering calling method.
    '     Entering called method, starting and awaiting Task.Delay.
    '   Returning from calling method.
    ' Exiting the Click event handler.
    '     Task.Delay is finished--returning from called method.
    
    
    ' Output
    
    ' Entering the Click event handler.
    '   Entering calling method.
    '     Entering called method, starting and awaiting Task.Delay.
    '     Task.Delay is finished--returning from called method.
    '   Returning from calling method.
    ' Exiting the Click event handler.
    
  5. Escolha a tecla F5 para executar o programa, e então escolha o botão de Iniciar .

    A saída previstas aparecem no final do código.

Consulte também

Referência

Operador Await (Visual Basic)

Conceitos

Programação assíncrona com Async e Await (C# e Visual Basic)