Lingua

Polling in applicazioni console

Installare il pacchetto NuGet Microsoft.Data.SqlClient per usare questo esempio. I metodi BeginExecuteNonQuery e EndExecuteNonQuery rimangono supportati. Non richiedono un'opzione asincrona della stringa di connessione. Non aggiungere Asynchronous Processing=true; Microsoft.Data.SqlClient non supporta tale parola chiave. Per il nuovo codice, preferire ExecuteNonQueryAsync con await anziché un ciclo di polling.

Le operazioni asincrone in ADO.NET consentono di avviare operazioni di database che richiedono molto tempo in un thread durante l'esecuzione di altre attività in un altro thread. Nella maggior parte degli scenari, tuttavia, verrà raggiunto un punto in cui l'applicazione non deve continuare finché non viene completata l'operazione del database. In questi casi è utile eseguire il polling dell'operazione asincrona per determinare se l'operazione è stata completata o meno.

È possibile usare la proprietà IsCompleted per verificare se l'operazione è stata completata o meno.

Esempio

L'applicazione console seguente aggiorna i dati all'interno del AdventureWorks database di esempio, eseguendone il lavoro in modo asincrono. Per emulare un processo a esecuzione prolungata, in questo esempio viene inserita un'istruzione WAITFOR nel testo del comando. In genere non si tenta di rallentare l'esecuzione dei comandi, ma in questo caso diventa più semplice dimostrare il comportamento asincrono.

Sostituire i puntini di sospensione restituiti da GetConnectionString con la stringa di connessione. Per un server remoto con autenticazione integrata di Windows, usare Server=<server>;Database=<database>;Integrated Security=true;Encrypt=true. Sostituire <server> e <database> con i nomi del server e del database e configurare un certificato server attendibile dal client. Per altre opzioni di autenticazione, vedere Sintassi della stringa di connessione.

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

Vedi anche