Langue

Interrogation dans les applications console

Installez le package NuGet Microsoft.Data.SqlClient pour utiliser cet exemple. Les BeginExecuteNonQuery et EndExecuteNonQuery restent prises en charge. Ces éléments ne nécessitent pas d’option de chaîne de connexion asynchrone. N'ajoutez pas Asynchronous Processing=true; Microsoft.Data.SqlClient ne prend pas en charge ce mot clé. Pour le nouveau code, préférez ExecuteNonQueryAsync avec await au lieu d’une boucle d’interrogation.

Les opérations asynchrones dans ADO.NET vous permettent de lancer des opérations de base de données qui prennent du temps sur un thread tout en effectuant d’autres tâches sur un autre thread. Dans la plupart des scénarios, toutefois, vous finirez par atteindre un point où votre application doit s'arrêter jusqu'à ce que l'opération de base de données soit terminée. Dans ce cas, il est utile d’interroger l’opération asynchrone pour déterminer si l’opération est terminée ou non.

Vous pouvez utiliser la propriété IsCompleted pour déterminer si l’opération est terminée ou non.

Exemple

L’application console suivante met à jour les données dans la base de données exemple AdventureWorks, effectuant son travail de manière asynchrone. Pour émuler un processus de longue durée, cet exemple insère une WAITFOR instruction dans le texte de la commande. Normalement, vous ne devez pas essayer de ralentir vos commandes, mais dans ce cas, cela simplifie l’illustration du comportement asynchrone.

Remplacez les points de suspension retournés par GetConnectionString par votre chaîne de connexion. Pour un serveur distant avec l’authentification intégrée Windows, utilisez Server=<server>;Database=<database>;Integrated Security=true;Encrypt=true. Remplacez <database> et <server> par les noms de votre serveur et de votre base de données, puis configurez un certificat de serveur approuvé par le client. Pour obtenir d’autres options d’authentification, consultez la syntaxe de chaîne de connexion.

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 "...";
    }
}

Voir aussi