Sprache

Abfragen in Konsolenanwendungen

Installieren Sie das Microsoft.Data.SqlClient-NuGet-Paket, um dieses Beispiel zu verwenden. Die BeginExecuteNonQuery- und EndExecuteNonQuery-Methoden werden weiterhin unterstützt. Sie erfordern keine asynchrone Verbindungszeichenfolgenoption. Fügen Sie Asynchronous Processing=true nicht hinzu; Microsoft.Data.SqlClient unterstützt dieses Schlüsselwort nicht. Verwenden Sie für neuen Code lieber ExecuteNonQueryAsync mit await anstelle einer Abfrageschleife.

Mithilfe von asynchronen Vorgängen in ADO.NET können Sie zeitaufwendige Datenbankvorgänge auf einem Thread initiieren, während andere Tasks auf einem weiteren Thread ausgeführt werden. In den meisten Szenarios erreichen Sie jedoch irgendwann einen Punkt, an dem die Anwendung angehalten werden sollte, bis der Datenbankvorgang beendet ist. Dann ist es hilfreich, den asynchronen Vorgang abzurufen, um zu ermitteln, ob der Vorgang abgeschlossen wurde.

Sie können die Eigenschaft IsCompleted verwenden, um herauszufinden, ob der Vorgang abgeschlossen ist.

Beispiel

Die folgende Konsolenanwendung aktualisiert Daten in der AdventureWorks Beispieldatenbank und führt ihre Arbeit asynchron aus. Um einen lang laufenden Prozess zu emulieren, fügt dieses Beispiel eine WAITFOR Anweisung in den Befehlstext ein. Normalerweise ist es nicht wünschenswert, dass Befehle langsamer ausgeführt werden, aber in diesem Fall kann dadurch das asynchrone Verhalten besser veranschaulicht werden.

Ersetzen Sie die von GetConnectionString zurückgegebenen Auslassungspunkte durch Ihre Verbindungszeichenfolge. Verwenden Sie Server=<server>;Database=<database>;Integrated Security=true;Encrypt=truefür einen Remoteserver mit Windows integrierter Authentifizierung . Ersetzen Sie <server> und <database> durch Ihre Server- und Datenbanknamen, und konfigurieren Sie ein Serverzertifikat, dem der Client vertraut. Weitere Authentifizierungsoptionen finden Sie unter Verbindungszeichenfolgensyntax.

Imports System
Imports Microsoft.Data.SqlClient

Module Module1

    Sub Main()
        ' The WAITFOR statement simply adds enough time to prove the
        ' asynchronous nature of the command.
        Dim commandText As String = _
         "UPDATE Production.Product " & _
         "SET ReorderPoint = ReorderPoint + 1 " & _
         "WHERE ReorderPoint Is Not Null;" & _
         "WAITFOR DELAY '0:0:3';" & _
         "UPDATE Production.Product " & _
         "SET ReorderPoint = ReorderPoint - 1 " & _
         "WHERE ReorderPoint Is Not Null"

        RunCommandAsynchronously(commandText, GetConnectionString())

        Console.WriteLine("Press Enter to continue.")
        Console.ReadLine()
    End Sub

    Private Sub RunCommandAsynchronously( _
     ByVal commandText As String, ByVal connectionString As String)

        ' Given command text and connection string, asynchronously
        ' execute the specified command against the connection. For
        ' this example, the code displays an indicator as it's working,
        ' verifying the asynchronous behavior.
        Using connection As New SqlConnection(connectionString)
            Try
                Dim count As Integer = 0
                Dim command As New SqlCommand(commandText, connection)
                connection.Open()
                Dim result As IAsyncResult = _
                 command.BeginExecuteNonQuery()
                While Not result.IsCompleted
                    Console.WriteLine("Waiting ({0})", count)
                    ' Wait for 1/10 second, so the counter
                    ' doesn't consume all available resources
                    ' on the main thread.
                    Threading.Thread.Sleep(100)
                    count += 1
                End While
                Console.WriteLine( _
                 "Command complete. Affected {0} rows.", _
                 command.EndExecuteNonQuery(result))
            Catch ex As SqlException
                Console.WriteLine("Error ({0}): {1}", _
                 ex.Number, ex.Message)
            Catch ex As InvalidOperationException
                Console.WriteLine("Error: {0}", ex.Message)
            Catch ex As Exception
                ' You might want to pass these errors
                ' back out to the caller.
                Console.WriteLine("Error: {0}", ex.Message)
            End Try
        End Using
    End Sub

    Private Function GetConnectionString() As String
        ' To avoid storing the connection string in your code,
        ' you can retrieve it from a configuration file.

        Return "..."
    End Function
End Module
using System;
using System.Data;
using Microsoft.Data.SqlClient;

class Class1
{
    [STAThread]
    static void Main()
    {
        // The WAITFOR statement simply adds enough time to
        // prove the asynchronous nature of the command.

        string commandText =
          "UPDATE Production.Product SET ReorderPoint = " +
          "ReorderPoint + 1 " +
          "WHERE ReorderPoint Is Not Null;" +
          "WAITFOR DELAY '0:0:3';" +
          "UPDATE Production.Product SET ReorderPoint = " +
          "ReorderPoint - 1 " +
          "WHERE ReorderPoint Is Not Null";

        RunCommandAsynchronously(
            commandText, GetConnectionString());

        Console.WriteLine("Press Enter to continue.");
        Console.ReadLine();
    }

    private static void RunCommandAsynchronously(
      string commandText, string connectionString)
    {
        // Given command text and connection string, asynchronously
        // execute the specified command against the connection.
        // For this example, the code displays an indicator as it's
        // working, verifying the asynchronous behavior.
        using (SqlConnection connection =
          new SqlConnection(connectionString))
        {
            try
            {
                int count = 0;
                SqlCommand command =
                    new SqlCommand(commandText, connection);
                connection.Open();

                IAsyncResult result =
                    command.BeginExecuteNonQuery();
                while (!result.IsCompleted)
                {
                    Console.WriteLine(
                                    "Waiting ({0})", count++);
                    // Wait for 1/10 second, so the counter
                    // doesn't consume all available
                    // resources on the main thread.
                    System.Threading.Thread.Sleep(100);
                }
                Console.WriteLine(
                    "Command complete. Affected {0} rows.",
                command.EndExecuteNonQuery(result));
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error ({0}): {1}",
                    ex.Number, ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                // You might want to pass these errors
                // back out to the caller.
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
    }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrieve it from a configuration file.

        return "...";
    }
}

Siehe auch