Partager via


BC42358 : étant donné que cet appel n’est pas attendu, l’exécution de la méthode actuelle se poursuit avant la fin de l’appel.

Étant donné que cet appel n’est pas attendu, l’exécution de la méthode actuelle se poursuit avant la fin de l’appel. Envisagez d’appliquer l’opérateur Await au résultat de l’appel.

La méthode actuelle appelle une méthode asynchrone qui retourne un Task ou un Task<TResult> et n’applique pas l’opérateur Await au résultat. L’appel à la méthode asynchrone démarre une tâche asynchrone. Toutefois, étant donné qu’aucun opérateur n’est Await appliqué, le programme continue sans attendre la fin de la tâche. Dans la plupart des cas, ce comportement n’est pas attendu. En règle générale, d’autres aspects de la méthode d’appel dépendent des résultats de l’appel ou, au minimum, la méthode appelée est censée se terminer avant de revenir de la méthode qui contient l’appel.

Un problème tout aussi important est ce qui se passe avec les exceptions soulevées dans la méthode asynchrone appelée. Exception levée dans une méthode qui retourne une Task ou Task<TResult> est stockée dans la tâche retournée. Si vous n’attendez pas la tâche ou vérifiez explicitement les exceptions, l’exception est perdue. Si vous attendez la tâche, son exception est réinitulative.

En guise de meilleure pratique, vous devez toujours attendre l’appel.

Par défaut, ce message est un avertissement. Pour plus d’informations sur le masquage des avertissements ou le traitement des avertissements en tant qu’erreurs, consultez Configuration d’avertissements en Visual Basic.

ID d’erreur : BC42358

Pour résoudre cet avertissement

Vous devez envisager de supprimer l’avertissement uniquement si vous êtes sûr que vous ne souhaitez pas attendre que l’appel asynchrone se termine et que la méthode appelée ne déclenche aucune exception. Dans ce cas, vous pouvez supprimer l’avertissement en affectant le résultat de la tâche de l’appel à une variable.

L’exemple suivant montre comment provoquer l’avertissement, comment le supprimer et comment attendre l’appel :

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

Dans l’exemple, si vous choisissez Appeler #1 ou Appeler #2, la méthode asynchrone non supervisée (CalledMethodAsync) se termine une fois que son appelant (CallingMethodAsync) et l’appelant (StartButton_Click) sont terminés. La dernière ligne de la sortie suivante vous montre quand la méthode appelée se termine. L’entrée et la sortie du gestionnaire d’événements qui appellent CallingMethodAsync l’exemple complet sont marquées dans la sortie.

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.

Exemple :

L’application WPF (Windows Presentation Foundation) suivante contient les méthodes de l’exemple précédent. Les étapes suivantes configurent l’application :

  1. Créez une application WPF et nommez-la AsyncWarning.

  2. Dans Visual Studio Code Editor, choisissez l’onglet MainWindow.xaml .

    Si l’onglet n’est pas visible, ouvrez le menu contextuel de MainWindow.xaml dans l’Explorateur de solutions, puis choisissez Afficher le code.

  3. Remplacez le code dans la vue XAML de MainWindow.xaml par le code suivant :

    <Window x:Class="MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://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>
    

    Une fenêtre simple qui contient un bouton et une zone de texte s’affiche dans la vue Création de MainWindow.xaml.

    Pour plus d’informations sur le Concepteur XAML, consultez Création d’une interface utilisateur à l’aide du Concepteur XAML. Pour plus d’informations sur la création de votre propre interface utilisateur simple, consultez les sections « Pour créer une application WPF » et « Pour concevoir une simple procédure pas à pas WPF MainWindow » : accès au web à l’aide d’Async et Await.

  4. Remplacez le code dans MainWindow.xaml.vb par le code suivant.

    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. Choisissez la touche F5 pour exécuter le programme, puis choisissez le bouton Démarrer .

    La sortie attendue apparaît à la fin du code.

Voir aussi