Export (0) Print
Expand All

SqlCommand.BeginExecuteReader Method (CommandBehavior)

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

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

'Declaration
<HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading := True)> _
Public Function BeginExecuteReader ( _
	behavior As CommandBehavior _
) As IAsyncResult

Parameters

behavior
Type: System.Data.CommandBehavior

One of the CommandBehavior values, indicating options for statement execution and data retrieval.

Return Value

Type: System.IAsyncResult
An IAsyncResult that can be used to poll, 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.

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 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.

The behavior parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's OR operator); generally, developers use the CommandBehavior.CloseConnection value to make sure that the connection is closed by the runtime when the SqlDataReader is closed.

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 BeginExecuteNonQuery 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 returns 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.

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 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. Once the process has completed, the code retrieves the SqlDataReader and displays its contents.

This example also passes the CommandBehavior.CloseConnection and CommandBehavior.SingleRow values in the behavior parameter, causing the connection to be closed with the returned SqlDataReader is closed, and to optimize for a single row result.

Imports System.Data.SqlClient

Module Module1
    Sub Main()
        ' This example is not terribly useful, but it proves a point. 
        ' 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 ProductID, Name FROM Production.Product WHERE ListPrice < 100"

        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.  
        Try 
            ' The code does not need to handle closing the connection explicitly-- 
            ' the use of the CommandBehavior.CloseConnection option takes care 
            ' of that for you.  
            Dim connection As New SqlConnection(connectionString)
            Dim command As New SqlCommand(commandText, connection)

            connection.Open()
            Dim result As IAsyncResult = _
              command.BeginExecuteReader(CommandBehavior.CloseConnection)

            ' Although it is not necessary, the following code 
            ' displays a counter in the console window, indicating that  
            ' the main thread is not blocked while awaiting the command  
            ' results. 
            Dim count As Integer = 0
            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.
                Threading.Thread.Sleep(100)
            End While 

            ' The "using" statement closes the SqlDataReader when it is  
            ' done executing. 
            Using reader As SqlDataReader = command.EndExecuteReader(result)
                DisplayResults(reader)
            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 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))
            Next
            Console.WriteLine()
        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

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

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.

Show:
© 2014 Microsoft