Delen via


SqlCommand.BeginExecuteXmlReader Method

Definition

Overloads

BeginExecuteXmlReader()

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object.

BeginExecuteXmlReader(AsyncCallback, Object)

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object, using a callback procedure.

BeginExecuteXmlReader()

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object.

public:
 IAsyncResult ^ BeginExecuteXmlReader();
public IAsyncResult BeginExecuteXmlReader ();
member this.BeginExecuteXmlReader : unit -> IAsyncResult
Public Function BeginExecuteXmlReader () As IAsyncResult

Returns

An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndExecuteXmlReader , which returns a single XML value.

Exceptions

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

-or-

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

-or-

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

Any error that occurred while executing the command text.

-or-

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

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

- or -

<xref data-throw-if-not-resolved="true" uid="Microssoft.Data.SqlClient.SqlCommand.EnableOptimizedParameterBinding"></xref>
is set to true and a parameter with direction Output or InputOutput has been added to the <xref data-throw-if-not-resolved="true" uid="Microsoft.Data.SqlClient.SqlCommand.Parameters"></xref> collection.

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.

Examples

The following console application starts the process of retrieving XML data 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 XML and displays its contents.

[!code-csharp[SqlCommand_BeginExecuteXmlReader#1]((~/../sqlclient/doc/samples/SqlCommand_BeginExecuteXmlReader.cs)]

Remarks

The BeginExecuteXmlReader method starts the process of asynchronously executing a Transact-SQL statement that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the EndExecuteXmlReader method to finish the operation and retrieve the XML returned by the command. The BeginExecuteXmlReader method returns immediately, but until the code executes the corresponding EndExecuteXmlReader method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same SqlCommand object. Calling the EndExecuteXmlReader before the command's execution is completed causes the SqlCommand object to block until the execution is finished.

The CommandText property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, CommandText can also specify a statement that returns ntext data that contains valid XML.

A typical BeginExecuteXmlReader query can be formatted as in the following C# example:

SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM dbo.Contact FOR XML AUTO, XMLDATA", SqlConn);

This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the EndExecuteXmlReader method attaches the XmlReader to the value on the first row, and discards the rest of the result set.

The multiple active result set (MARS) feature lets multiple actions use the same connection.

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.

Because this overload does not support a callback procedure, developers need to either poll to determine whether the command has completed, using the IsCompleted property of the IAsyncResult returned by the BeginExecuteXmlReader 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.

This method ignores the CommandTimeout property.

Applies to

BeginExecuteXmlReader(AsyncCallback, Object)

Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object, using a callback procedure.

public:
 IAsyncResult ^ BeginExecuteXmlReader(AsyncCallback ^ callback, System::Object ^ stateObject);
public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object stateObject);
member this.BeginExecuteXmlReader : AsyncCallback * obj -> IAsyncResult
Public Function BeginExecuteXmlReader (callback As AsyncCallback, stateObject As Object) As IAsyncResult

Parameters

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

Returns

An IAsyncResult that can be used to poll, wait for results, or both; this value is also needed when the EndExecuteXmlReader(IAsyncResult) is called, which returns the results of the command as XML.

Exceptions

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

-or-

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

-or-

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

Any error that occurred while executing the command text.

-or-

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

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

- or -

<xref data-throw-if-not-resolved="true" uid="Microssoft.Data.SqlClient.SqlCommand.EnableOptimizedParameterBinding"></xref>
is set to true and a parameter with direction Output or InputOutput has been added to the <xref data-throw-if-not-resolved="true" uid="Microsoft.Data.SqlClient.SqlCommand.Parameters"></xref> collection.

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.

Examples

The following Windows application demonstrates the use of the BeginExecuteXmlReader method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). 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 EndExecuteXmlReader method corresponding to the initial call to BeginExecuteXmlReader.

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

// <Snippet1>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Data.SqlClient;
using System.Xml;

namespace Microsoft.AdoDotNet.CodeSamples
{
    public partial class Form1 : Form
    {
        // Hook up the form's Load event handler and then add 
        // this code to the form's class:
        // You need these delegates in order to display text from a thread
        // other than the form's thread. See the HandleCallback
        // procedure for more information.
        private delegate void DisplayInfoDelegate(string Text);
        private delegate void DisplayReaderDelegate(XmlReader reader);

        private bool isExecuting;

        // This example maintains the connection object 
        // externally, so that it is available for closing.
        private SqlConnection connection;

        public Form1()
        {
            InitializeComponent();
        }

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

            return "Data Source=(local);Integrated Security=true;" +
            "Initial Catalog=AdventureWorks";
        }

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

        private void ClearProductInfo()
        {
            // Clear the list box.
            this.listBox1.Items.Clear();
        }

        private void DisplayProductInfo(XmlReader reader)
        {
            // Display the data within the reader.
            while (reader.Read())
            {
                // Skip past items that are not from the correct table.
                if (reader.LocalName.ToString() == "Production.Product")
                {
                    this.listBox1.Items.Add(String.Format("{0}: {1:C}",
                        reader["Name"], Convert.ToDecimal(reader["ListPrice"])));
                }
            }
            DisplayStatus("Ready");
        }

        private void Form1_FormClosing(object sender,
            System.Windows.Forms.FormClosingEventArgs e)
        {
            if (isExecuting)
            {
                MessageBox.Show(this, "Cannot close the form until " +
                    "the pending asynchronous command has completed. Please wait...");
                e.Cancel = 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
                {
                    ClearProductInfo();
                    DisplayStatus("Connecting...");
                    connection = new SqlConnection(GetConnectionString());

                    // To emulate a long-running query, wait for 
                    // a few seconds before working with the data.
                    string commandText =
                        "WAITFOR DELAY '00:00:03';" +
                        "SELECT Name, ListPrice FROM Production.Product " +
                        "WHERE ListPrice < 100 " +
                        "FOR XML AUTO, XMLDATA";

                    command = new SqlCommand(commandText, connection);
                    connection.Open();

                    DisplayStatus("Executing...");
                    isExecuting = true;
                    // Although it is not required that you pass the 
                    // SqlCommand object as the second parameter in the 
                    // BeginExecuteXmlReader call, doing so makes it easier
                    // to call EndExecuteXmlReader in the callback procedure.
                    AsyncCallback callback = new AsyncCallback(HandleCallback);
                    command.BeginExecuteXmlReader(callback, command);

                }
                catch (Exception ex)
                {
                    isExecuting = false;
                    DisplayStatus(string.Format("Ready (last error: {0})", ex.Message));
                    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;
                XmlReader reader = command.EndExecuteXmlReader(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. 

                // 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. 
                DisplayReaderDelegate del = new DisplayReaderDelegate(DisplayProductInfo);
                this.Invoke(del, reader);

            }
            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 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:
                this.Invoke(new DisplayInfoDelegate(DisplayStatus),
                String.Format("Ready(last error: {0}", ex.Message));
            }
            finally
            {
                isExecuting = false;
                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 System.Windows.Forms.
                FormClosingEventHandler(this.Form1_FormClosing);
        }
    }
}
// </Snippet1>

Remarks

The BeginExecuteXmlReader method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the EndExecuteXmlReader method to finish the operation and retrieve the requested XML data. The BeginExecuteXmlReader method returns immediately, but until the code executes the corresponding EndExecuteXmlReader method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same SqlCommand object. Calling the EndExecuteXmlReader before the command's execution is completed causes the SqlCommand object to block until the execution is finished.

The CommandText property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, CommandText can also specify a statement that returns data that contains valid XML. This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the EndExecuteXmlReader method attaches the XmlReader to the value on the first row, and discards the rest of the result set.

A typical BeginExecuteXmlReader query can be formatted as in the following C# example:

SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM Contact FOR XML AUTO, XMLDATA", SqlConn);

This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the EndExecuteXmlReader method attaches the XmlReader to the value on the first row, and discards the rest of the result set.

The multiple active result set (MARS) feature lets multiple actions use the same connection.

The callback parameter lets you specify an AsyncCallback delegate that is called when the statement has completed. You can call the EndExecuteXmlReader 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 is 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.

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

This method ignores the CommandTimeout property.

See also

Applies to