SqlCommand.BeginExecuteNonQuery Method (AsyncCallback, Object)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, given a callback procedure and state information.

Namespace:   System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)

<HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading := True)>
Public Function BeginExecuteNonQuery (
	callback As AsyncCallback,
	stateObject As Object
) As IAsyncResult


Type: System.AsyncCallback

An AsyncCallback delegate that is invoked when the command's execution has completed. Pass null (Nothing in Microsoft Visual Basic) to indicate that no callback is required.

Type: System.Object

A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the AsyncState property.

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.

Exception Condition

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.


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.


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.


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


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.

The callback parameter lets you specify an AsyncCallback delegate that is called when the statement has completed. You can call the EndExecuteNonQuery method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the asyncStateObject parameter, and your callback procedure can retrieve this information using the AsyncState property.

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 the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior.

All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure.

The following Windows application demonstrates the use of the BeginExecuteNonQuery method, executing a Transact-SQL statement that includes a delay of several seconds (emulating a long-running command).

This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called.

To set up this example, create a new Windows application. Put a Button control and a Label control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment.

Imports System.Data.SqlClient

Public Class Form1
    ' Add this code to the form's class:
    ' You need this delegate in order to display text from a thread
    ' other than the form's thread. See the HandleCallback
    ' procedure for more information.
    ' This same delegate matches both the DisplayStatus 
    ' and DisplayResults methods.
    Private Delegate Sub DisplayInfoDelegate(ByVal Text As String)

    ' This flag ensures that the user does not attempt
    ' to restart the command or close the form while the 
    ' asynchronous command is executing.
    Private isExecuting As Boolean

    ' This example maintains the connection object 
    ' externally, so that it is available for closing.
    Private connection As SqlConnection

    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=true;" & _
          "Initial Catalog=AdventureWorks; Asynchronous Processing=true"
    End Function

    Private Sub DisplayStatus(ByVal Text As String)
        Me.Label1.Text = Text
    End Sub

    Private Sub DisplayResults(ByVal Text As String)
        Me.Label1.Text = Text
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.FormClosingEventArgs) _
        Handles Me.FormClosing
        If isExecuting Then
            MessageBox.Show(Me, "Cannot close the form until " & _
                "the pending asynchronous command has completed. Please wait...")
            e.Cancel = True
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        If isExecuting Then
            MessageBox.Show(Me, _
               "Already executing. Please wait until the current query " & _
                "has completed.")
            Dim command As SqlCommand
                connection = New SqlConnection(GetConnectionString())
                ' To emulate a long-running query, wait for 
                ' a few seconds before working with the data.
                ' This command does not do much, but that's the point--
                ' it does not change your data, in the long run.
                Dim commandText As String = _
                    "WAITFOR DELAY '0:0:05';" & _
                    "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " & _
                    "WHERE ReorderPoint Is Not Null;" & _
                    "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " & _
                    "WHERE ReorderPoint Is Not Null"

                command = New SqlCommand(commandText, connection)

                isExecuting = True
                ' Although it is not required that you pass the 
                ' SqlCommand object as the second parameter in the 
                ' BeginExecuteNonQuery call, doing so makes it easier
                ' to call EndExecuteNonQuery in the callback procedure.
                Dim callback As New AsyncCallback(AddressOf HandleCallback)
                command.BeginExecuteNonQuery(callback, command)

            Catch ex As Exception
                isExecuting = False
                DisplayStatus(String.Format("Ready (last error: {0})", ex.Message))
                If connection IsNot Nothing Then
                End If
            End Try
        End If
    End Sub

    Private Sub HandleCallback(ByVal result As IAsyncResult)
            ' Retrieve the original command object, passed
            ' to this procedure in the AsyncState property
            ' of the IAsyncResult parameter.
            Dim command As SqlCommand = CType(result.AsyncState, SqlCommand)
            Dim rowCount As Integer = command.EndExecuteNonQuery(result)
            Dim rowText As String = " rows affected."
            If rowCount = 1 Then
                rowText = " row affected."
            End If
            rowText = rowCount & rowText

            ' You may not interact with the form and its contents
            ' from a different thread, and this callback procedure
            ' is all but guaranteed to be running from a different thread
            ' than the form. Therefore you cannot simply call code that 
            ' displays the results, like this:
            ' DisplayResults(rowText)

            ' Instead, you must call the procedure from the form's thread.
            ' One simple way to accomplish this is to call the Invoke
            ' method of the form, which calls the delegate you supply
            ' from the form's thread. 
            Dim del As New DisplayInfoDelegate(AddressOf DisplayResults)
            Me.Invoke(del, rowText)

        Catch ex As Exception
            ' Because you are now running code in a separate thread, 
            ' if you do not handle the exception here, none of your other
            ' code catches the exception. Because none of your code
            ' is on the call stack in this thread, there is nothing
            ' higher up the stack to catch the exception if you do not 
            ' handle it here. You can either log the exception or 
            ' invoke a delegate (as in the non-error case in this 
            ' example) to display the error on the form. In no case
            ' can you simply display the error without executing a delegate
            ' as in the Try block here. 

            ' You can create the delegate instance as you 
            ' invoke it, like this:
            Me.Invoke(New DisplayInfoDelegate(AddressOf DisplayStatus), _
                String.Format("Ready(last error: {0}", ex.Message))
            isExecuting = False
            If connection IsNot Nothing Then
            End If
        End Try
    End Sub
End Class

.NET Framework
Available since 2.0
Return to top