Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

SqlCommand.BeginExecuteNonQuery Method

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand.

Namespace:  System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)
[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public IAsyncResult BeginExecuteNonQuery()

Return Value

Type: System.IAsyncResult
An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndExecuteNonQuery, which returns the number of affected rows.
ExceptionCondition
InvalidCastException

A SqlDbType other than Binary or VarBinary was used when Value was set to Stream. For more information about streaming, see SqlClient Streaming Support.

A SqlDbType other than Char, NChar, NVarChar, VarChar, or Xml was used when Value was set to TextReader.

A SqlDbType other than Xml was used when Value was set to XmlReader.

SqlException

Any error that occurred while executing the command text.

A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support.

InvalidOperationException

The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this SqlCommand.

The SqlConnection closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support.

IOException

An error occurred in a Stream, XmlReader or TextReader object during a streaming operation. For more information about streaming, see SqlClient Streaming Support.

ObjectDisposedException

The Stream, XmlReader or TextReader object was closed during a streaming operation. For more information about streaming, see SqlClient Streaming Support.

The BeginExecuteNonQuery method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the EndExecuteNonQuery method to finish the operation. The BeginExecuteNonQuery method returns immediately (CommandTimeout has no effect on BeginExecuteNonQuery), but until the code executes the corresponding EndExecuteNonQuery method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same SqlCommand object. Calling the EndExecuteNonQuery before the command's execution is completed causes the SqlCommand object to block until the execution is finished.

Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous.

Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the IsCompleted property of the IAsyncResult returned by the BeginExecuteNonQuery method; or wait for the completion of one or more commands using the AsyncWaitHandle property of the returned IAsyncResult.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following console application creates updates data within the AdventureWorks sample database, doing its work asynchronously. In order to emulate a long-running process, this example inserts a WAITFOR statement in the command text. Normally, you would not take efforts to make your commands run slower, but doing this in this case makes it easier to demonstrate the asynchronous behavior.

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

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.