Export (0) Print
Expand All

SqlCommand.BeginExecuteReader Method (AsyncCallback, Object)

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, given a callback procedure and state information.

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

[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public IAsyncResult BeginExecuteReader(
	AsyncCallback callback,
	Object stateObject
)

Parameters

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

stateObject
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, wait for results, or both; this value is also needed when invoking EndExecuteReader, which returns a SqlDataReader instance which 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 cause 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 EndExecuteReader method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the stateObject 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. 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 the callback procedure executes from within a background thread supplied by the Microsoft .NET 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.

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 Windows application demonstrates the use of the BeginExecuteReader method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing SqlCommand object as the stateObject parameter; doing so makes it simple to retrieve the SqlCommand object from within the callback procedure, so that the code can call the EndExecuteReader method corresponding to the initial call to BeginExecuteReader.

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, a DataGridView 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.

using System.Data.SqlClient;

namespace Microsoft.AdoDotNet.CodeSamples
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Hook up the form's Load event handler (you can double-click on  
        // the form's design surface in Visual Studio), and then add  
        // this code to the form's class: 

        // You need this delegate in order to fill the grid from 
        // a thread other than the form's thread. See the HandleCallback 
        // procedure for more information. 
        private delegate void FillGridDelegate(SqlDataReader reader);

        // You need this delegate to update the status bar. 
        private delegate void DisplayStatusDelegate(string Text);

        // This flag ensures that the user does not attempt 
        // to restart the command or close the form while the  
        // asynchronous command is executing. 
        private bool isExecuting = false;

        // Because the overloaded version of BeginExecuteReader 
        // demonstrated here does not allow you to have the connection 
        // closed automatically, this example maintains the  
        // connection object externally, so that it is available for closing. 
        private SqlConnection connection = null;

        private void DisplayStatus(string Text)
        {
            this.label1.Text = Text;
        }

        private void FillGrid(SqlDataReader reader)
        {
            try
            {
                DataTable table = new DataTable();
                table.Load(reader);
                this.dataGridView1.DataSource = table;
                DisplayStatus("Ready");
            }
            catch (Exception ex)
            {
                // Because you are guaranteed this procedure 
                // is running from within the form's thread, 
                // it can directly interact with members of the form.
                DisplayStatus(string.Format("Ready (last attempt failed: {0})",
                    ex.Message));
            }
            finally
            {
                // Do not forget to close the connection, as well. 
                if (reader != null)
                {
                    reader.Close();
                }
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }

        private void HandleCallback(IAsyncResult result)
        {
            try
            {
                // Retrieve the original command object, passed 
                // to this procedure in the AsyncState property 
                // of the IAsyncResult parameter.
                SqlCommand command = (SqlCommand)result.AsyncState;
                SqlDataReader reader = command.EndExecuteReader(result);
                // 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  
                // fills the grid, like this: 
                // FillGrid(reader); 
                // 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. 
                FillGridDelegate del = new FillGridDelegate(FillGrid);
                this.Invoke(del, reader);
                // Do not close the reader here, because it is being used in  
                // a separate thread. Instead, have the procedure you have 
                // called close the reader once it is done with it.
            }
            catch (Exception ex)
            {
                // 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 there is none of  
                // your code 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: 
                this.Invoke(new DisplayStatusDelegate(DisplayStatus),
                    "Error: " + ex.Message);
            }
            finally
            {
                isExecuting = false;
            }
        }

        private string GetConnectionString()
        {
            // To avoid storing the connection string in your code,  
            // you can retrieve it from a configuration file.  

            // If you do not include the Asynchronous Processing=true name/value pair, 
            // you wo not be able to execute the command asynchronously. 
            return "Data Source=(local);Integrated Security=true;" +
                "Initial Catalog=AdventureWorks; Asynchronous Processing=true";
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            if (isExecuting)
            {
                MessageBox.Show(this,
                    "Already executing. Please wait until the current query " +
                    "has completed.");
            }
            else
            {
                SqlCommand command = null;
                try
                {
                    DisplayStatus("Connecting...");
                    connection = new SqlConnection(GetConnectionString());
                    // To emulate a long-running query, wait for  
                    // a few seconds before retrieving the real data.
                    command = new SqlCommand("WAITFOR DELAY '0:0:5';" +
                        "SELECT ProductID, Name, ListPrice, Weight FROM Production.Product",
                        connection);
                    connection.Open();

                    DisplayStatus("Executing...");
                    isExecuting = true;
                    // Although it is not required that you pass the  
                    // SqlCommand object as the second parameter in the  
                    // BeginExecuteReader call, doing so makes it easier 
                    // to call EndExecuteReader in the callback procedure.
                    AsyncCallback callback = new AsyncCallback(HandleCallback);
                    command.BeginExecuteReader(callback, command);
                }
                catch (Exception ex)
                {
                    DisplayStatus("Error: " + ex.Message);
                    if (connection != null)
                    {
                        connection.Close();
                    }
                }
            }
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            this.button1.Click += new System.EventHandler(this.button1_Click);
            this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isExecuting)
            {
                MessageBox.Show(this, "Cannot close the form until " +
                    "the pending asynchronous command has completed. Please wait...");
                e.Cancel = true;
            }
        }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 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