Assembly: System.Data (in system.data.dll)
Public Function BeginExecuteXmlReader As IAsyncResult
Dim instance As SqlCommand Dim returnValue As IAsyncResult returnValue = instance.BeginExecuteXmlReader
public IAsyncResult BeginExecuteXmlReader ()
public:
IAsyncResult^ BeginExecuteXmlReader ()
public IAsyncResult BeginExecuteXmlReader ()
public function BeginExecuteXmlReader () : IAsyncResult
Return Value
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.| Exception type | Condition |
|---|---|
| Any error that occurred while executing the command text. |
|
| The name/value pair "Asynchronous Processing=true" was not included within the connection string defining the connection for this SqlCommand. |
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);
Note |
|---|
| This type of query only works with Microsoft SQL Server 2000 or later versions. For more information, see "Guidelines for Using the FOR XML Clause" in SQL Server Books Online. |
When used with SQL Server 2005, 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.
When you use versions of SQL Server earlier than SQL Server 2005, while the XmlReader is being used the associated SqlConnection is busy serving the XmlReader. While in this state, no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the XmlReader is called. Starting with SQL Server 2005, 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. 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 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.
Imports System.Data.SqlClient Imports System.Xml Module Module1 Sub Main() ' This example is not terribly effective, 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 Name, ListPrice FROM Production.Product " & _ "WHERE ListPrice < 100 " & _ "FOR XML AUTO, XMLDATA" 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. Using connection As New SqlConnection(connectionString) Try Dim command As New SqlCommand(commandText, connection) connection.Open() Dim result As IAsyncResult = command.BeginExecuteXmlReader() ' 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 = 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 Using reader As XmlReader = command.EndExecuteXmlReader(result) DisplayProductInfo(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 Using End Sub Private Sub DisplayProductInfo(ByVal reader As XmlReader) ' 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" Then Console.WriteLine("{0: {1:C", _ reader("Name"), CSng(reader("ListPrice"))) End If 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
using System.Data.SqlClient; using System.Xml; class Class1 { static void Main() { // This example is not terribly effective, but it proves a point. // The WAITFOR statement simply adds enough time to prove the // asynchronous nature of the command. string commandText = "WAITFOR DELAY '00:00:03';" + "SELECT Name, ListPrice FROM Production.Product " + "WHERE ListPrice < 100 " + "FOR XML AUTO, XMLDATA"; RunCommandAsynchronously(commandText, GetConnectionString()); Console.WriteLine("Press ENTER to continue."); Console.ReadLine(); private static void RunCommandAsynchronously( string commandText, string connectionString) { // 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 (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(commandText, connection); connection.Open(); IAsyncResult result = command.BeginExecuteXmlReader(); // 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. int count = 0; while (!result.IsCompleted) { Console.WriteLine("Waiting ({0)", count++); // Wait for 1/10 second, so the counter // does not consume all available resources // on the main thread. System.Threading.Thread.Sleep(100); XmlReader reader = command.EndExecuteXmlReader(result); DisplayProductInfo(reader); private static 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") { Console.WriteLine("{0: {1:C", reader["Name"], Convert.ToSingle(reader["ListPrice"])); private static string GetConnectionString() { // 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";
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.
Note