Udostępnij za pośrednictwem


Ostrzeżenie kompilatora (poziom 1) CS4014

Ponieważ to wywołanie nie jest oczekiwane, wykonywanie bieżącej metody będzie kontynuowane do czasu ukończenia wywołania.Rozważ zastosowanie operatora „await” do wyniku wywołania.

Bieżąca metoda wywołuje metodę komunikacji asynchronicznej, która zwraca Task lub Task<TResult> i nie ma zastosowania czekają na operatora do wyniku.Wywołanie metody asynchronicznej uruchamia zadanie asynchroniczne.Jednakże ponieważ nie await stosowany jest operator, program kontynuuje działanie bez oczekiwania na wykonanie zadania.W większości przypadków to zachowanie nie jest oczekiwana.Zazwyczaj inne aspekty metody wywołującej zależą od wyników wywołania, lub minimalny, oczekiwano ukończyć przed zwróceniem przez metodę, która zawiera wywołanie metody o nazwie.

Równie ważnym zagadnieniem jest, co się dzieje z wyjątków, które są wywoływane metody o nazwie asynchronicznej.Wyjątek, który jest wywoływane w metodzie, która zwraca Task lub Task<TResult> jest przechowywany w zwracanych zadania.Jeśli nie czekają na zadanie lub jawnego sprawdzani, wyjątki, wyjątek zostaną utracone.Jeśli możesz oczekiwać zadania, jego wyjątek jest rethrown.

Najlepszym rozwiązaniem należy zawsze czekają na wywołanie.

Należy rozważyć, pomijanie ostrzeżenia, tylko wtedy, gdy wiadomo, że nie chcesz czekać na asynchroniczne wywołanie do ukończenia i że metodę o nazwie nie podniesie żadnych wyjątków.W takim przypadku można pominąć wyświetlanie ostrzeżenia przypisując wynik zadania zaproszenia do zmiennej.

Poniższy przykład pokazuje, jak spowodować, że ostrzeżenie, jak wyłączyć go i jak czekają na wywołanie.

async Task CallingMethodAsync()
{
    resultsTextBox.Text += "\r\n  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.
    var 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 warning CS4014.
    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, 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. 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 += "\r\n  Returning from calling method.";
}


async Task CalledMethodAsync(int howLong)
{
    resultsTextBox.Text += 
        "\r\n    Entering called method, starting and awaiting Task.Delay.";

    // Slow the process down a little so that you can distinguish between
    // awaiting and not awaiting in the program's output. Adjust the value
    // for howLong if necessary.
    await Task.Delay(howLong);
    resultsTextBox.Text += 
        "\r\n    Task.Delay is finished--returning from called method.";
}

W przykładzie, jeśli wybierzesz wywołanie #1 lub wywołanie #2, metoda unawaited async (CalledMethodAsync) zakończy się po obu wywołującego (CallingMethodAsync) i wywołujący (startButton_Click) nie są zakończone.Ostatniej linii w następujące dane wyjściowe pokazuje, kiedy kończy się metodę o nazwie.Wejście do i wyjście z programu obsługi zdarzeń, który wywołuje CallingMethodAsync w pełny przykład są oznaczone w danych wyjściowych.

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.

Można również pominąć ostrzeżeń kompilatora przy użyciu # pragma ostrzeżenie (C# odniesienia) dyrektyw.

Przykład

Następująca aplikacja Windows Presentation Foundation (WPF) zawiera metody z poprzedniego przykładu.Poniższe czynności spowodują ustawienie tę aplikację.

  1. Tworzenie aplikacji WPF i nadaj mu nazwę AsyncWarning.

  2. Wybierz Visual Studio Edytor kodu, MainWindow.xaml kartę.

    Jeśli karta należy otworzyć menu skrótów dla MainWindow.xaml w Solution Explorer, a następnie wybierz polecenie View Code.

  3. Zastąp kod w XAML widok MainWindow.xaml z następującego kodu.

    <Window x:Class="AsyncWarning.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>
    

    Proste okno zawierające przycisk i pole tekstu pojawia się w Projekt widok MainWindow.xaml.

    Aby uzyskać więcej informacji o narzędziu Designer XAML, zobacz Creating a UI by using XAML Designer.Aby uzyskać informacje o tym, jak zbudować własny prosty interfejs użytkownika, zobacz "Aby utworzyć aplikację programu WPF" i "projektowania prostych MainWindow WPF" sekcje z Instruktaż: Dostęp do sieci Web za pomocą transmisji asynchronicznej i poczekać (C# i Visual Basic).

  4. Zastąp kod w MainWindow.xaml.cs z następującego kodu.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace AsyncWarning
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private async void startButton_Click(object sender, RoutedEventArgs e)
            {
                resultsTextBox.Text += "\r\nEntering the Click event handler.";
                await CallingMethodAsync();
                resultsTextBox.Text += "\r\nExiting the Click event handler.";
            }
    
    
            async Task CallingMethodAsync()
            {
                resultsTextBox.Text += "\r\n  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.
                var 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 warning CS4014.
                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, 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. 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 += "\r\n  Returning from calling method.";
            }
    
    
            async Task CalledMethodAsync(int howLong)
            {
                resultsTextBox.Text += 
                    "\r\n    Entering called method, starting and awaiting Task.Delay.";
    
                // Slow the process down a little so that you can distinguish between
                // awaiting and not awaiting in the program's output. Adjust the value
                // for howLong if necessary.
                await Task.Delay(howLong);
                resultsTextBox.Text += 
                    "\r\n    Task.Delay is finished--returning from called method.";
            }
        }
    
        // Output with Call #1 or Call #2. (Wait for the last line to appear.)
    
        // 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 with Call #3, which awaits the call to CalledMethodAsync.
    
        // 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. Wybierz klawisz F5, aby uruchomić program, a następnie wybierz Start przycisk.

    Przewidywanej produkcji pojawia się na końcu kodu.

Zobacz też

Informacje

poczekać (C# odniesienia)

Koncepcje

Asynchroniczne programowania przy użyciu asynchronicznej i poczekać (C# i Visual Basic)