Evaluar y enviar comentarios

  Encender vista de ancho de banda bajo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
SqlCommand.BeginExecuteNonQuery (Método) ()

Nota: este método es nuevo en la versión 2.0 de .NET Framework.

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand.

Espacio de nombres: System.Data.SqlClient
Ensamblado: System.Data (en system.data.dll)

Visual Basic (Declaración)
Public Function BeginExecuteNonQuery As IAsyncResult
Visual Basic (Uso)
Dim instance As SqlCommand
Dim returnValue As IAsyncResult

returnValue = instance.BeginExecuteNonQuery
C#
public IAsyncResult BeginExecuteNonQuery ()
C++
public:
IAsyncResult^ BeginExecuteNonQuery ()
J#
public IAsyncResult BeginExecuteNonQuery ()
JScript
public function BeginExecuteNonQuery () : IAsyncResult

Valor devuelto

IAsyncResult que se puede utilizar para sondear y/o esperar los resultados; este valor también es necesario al invocar a EndExecuteNonQuery, que devuelve el número de filas afectado.
Tipo de excepciónCondición

SqlException

Cualquier error que se haya producido al ejecutar el texto del comando.

InvalidOperationException

El par de nombre/valor "Asynchronous Processing=true" no se ha incluido en la cadena de conexión que define la conexión para este SqlCommand.

El método BeginExecuteNonQuery inicia el proceso de ejecución asincrónica de una instrucción de Transact-SQL o de un procedimiento almacenado que no devuelve filas, para que otras tareas puedan ejecutarse simultáneamente mientras se ejecuta la instrucción. Cuando termina la instrucción, los desarrolladores deben llamar al método EndExecuteNonQuery para finalizar la operación. El método BeginExecuteNonQuery devuelve un valor inmediatamente, pero hasta que el código ejecute la llamada al método EndExecuteNonQuery correspondiente, no debe ejecutar ninguna otra llamada que comience una ejecución sincrónica o asincrónica con respecto al mismo objeto SqlCommand. Si se llama a EndExecuteNonQuery antes de que finalice la ejecución del comando, el objeto SqlCommand se bloqueará hasta que la ejecución termine.

Observe que el texto del comando y los parámetros se envían al servidor de forma sincrónica. Si se envía un comando de gran tamaño o un gran número de parámetros, este método puede bloquearse durante las operaciones de escritura. Una vez enviado el comando, el método devuelve un valor inmediatamente sin esperar una respuesta del servidor; es decir, las lecturas son asincrónicas.

Dado que esta sobrecarga no admite un procedimiento de devolución de llamada, los desarrolladores deben sondear para determinar si el comando ha finalizado, utilizando la propiedad IsCompleted de IAsyncResult que devuelve el método BeginExecuteNonQuery, o bien, deben esperar a que finalice uno o varios comandos, utilizando la propiedad AsyncWaitHandle de IAsyncResult que se devuelve.

En la aplicación de consola siguiente se crean, de forma asincrónica, datos de actualización en la base de datos AdventureWorks de ejemplo. Para emular un proceso largo, en este ejemplo se inserta una instrucción WAITFOR en el texto del comando. Habitualmente uno no se molesta en hacer que los comandos se ejecuten más lentamente, pero haciéndolo así en este caso resulta más sencillo mostrar el comportamiento asincrónico.

Visual Basic
Imports System.Data.SqlClient

Module Module1

    Sub Main()
        ' This is a simple example that demonstrates the usage of the 
        ' BeginExecuteNonQuery functionality.
        ' 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 is 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
                    ' does not 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. 

        ' If you have not included "Asynchronous Processing=true" in the
        ' connection string, the command is not able
        ' to execute asynchronously.
        Return "Data Source=(local);Integrated Security=SSPI;" & _
          "Initial Catalog=AdventureWorks; Asynchronous Processing=true"
    End Function
End Module
C#
using System.Data.SqlClient;

class Class1
{
    static void Main()
    {
        // This is a simple example that demonstrates the usage of the 
        // BeginExecuteNonQuery functionality.
        // 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 is 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
                    // does not 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. 

        // If you have not included "Asynchronous Processing=true" in the
        // connection string, the command is not able
        // to execute asynchronously.
        return "Data Source=(local);Integrated Security=SSPI;" +
            "Initial Catalog=AdventureWorks; Asynchronous Processing=true";
    } 
}

Windows 98, Windows 2000 SP4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso  |  Marcas Registradas  |  Privacidad
Page view tracker