SqlCommand.BeginExecuteReader Method ()


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, and retrieves one or more result sets from the server.

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

<HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading := True)>
Public Function BeginExecuteReader As IAsyncResult

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 EndExecuteReader, which returns a SqlDataReader instance that can be used to retrieve the returned 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 BeginExecuteReader method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the EndExecuteReader method to finish the operation and retrieve the SqlDataReader returned by the command. The BeginExecuteReader method returns immediately, but until the code executes the corresponding EndExecuteReader method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same SqlCommand object. Calling the EndExecuteReader 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. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to Read may block if more data is required and the underlying network's read operation blocks.

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 BeginExecuteReader method; or wait for the completion of one or more commands using the AsyncWaitHandle property of the returned IAsyncResult.

If you use ExecuteReader or BeginExecuteReader to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use ExecuteXmlReader or BeginExecuteXmlReader to read FOR XML queries. For more information, see article Q310378, "PRB: XML Data Is Truncated When You Use SqlDataReader," in the Microsoft Knowledge Base at http://support.microsoft.com.

The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the IsCompleted property value. As soon as the process has completed, the code retrieves the SqlDataReader and displays its contents.

Imports System.Data.SqlClient

Module Module1
    Sub Main()
        ' This is a simple example that demonstrates the usage of the 
        ' BeginExecuteReader functionality.
        ' The WAITFOR statement simply adds enough time to prove the 
        ' asynchronous nature of the command.
        Dim commandText As String = _
         "WAITFOR DELAY '00:00:03';" & _
         "SELECT LastName, FirstName FROM Person.Contact " & _
         "WHERE LastName LIKE 'M%'"

        RunCommandAsynchronously(commandText, GetConnectionString())

        Console.WriteLine("Press ENTER to continue.")
    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)
                Dim command As New SqlCommand(commandText, connection)

                Dim result As IAsyncResult = command.BeginExecuteReader()

                ' Although it is not necessary, the following procedure
                ' displays a counter in the console window, indicating that 
                ' the main thread is not blocked while awaiting the command 
                ' results.
                Dim count As Integer
                While Not result.IsCompleted
                    count += 1
                    Console.WriteLine("Waiting ({0})", count)
                    ' Wait for 1/10 second, so the counter
                    ' does not consume all available resources 
                    ' on the main thread.
                End While

                ' Once the IAsyncResult object signals that it is done
                ' waiting for results, you can retrieve the results.
                Using reader As SqlDataReader = command.EndExecuteReader(result)
                End Using
            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 Sub DisplayResults(ByVal reader As SqlDataReader)
        ' Display the data within the reader.
        While reader.Read()
            ' Display all the columns.
            For i As Integer = 0 To reader.FieldCount - 1
                Console.Write("{0} ", reader.GetValue(i))
        End While
    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=true;" & _
          "Initial Catalog=AdventureWorks; Asynchronous Processing=true"
    End Function
End Module

.NET Framework
Available since 2.0
Return to top