SqlCommand.BeginExecuteXmlReader 메서드

정의

SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 결과를 XmlReader 개체로 반환합니다.

오버로드

BeginExecuteXmlReader()

SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 결과를 XmlReader 개체로 반환합니다.

BeginExecuteXmlReader(AsyncCallback, Object)

콜백 프로시저를 사용하여 이 SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 결과를 XmlReader 개체로 반환합니다.

BeginExecuteXmlReader()

SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 결과를 XmlReader 개체로 반환합니다.

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

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 단일 XML 값을 반환하는 EndExecuteXmlReader를 호출할 때도 이 값이 필요합니다.

예외

SqlDbType 로 설정된 Stream경우 ValueBinary 또는 VarBinary 이외의 가 사용되었습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

또는

이 로 SqlDbType 설정TextReader되었을 때 ValueChar, NChar, NVarChar, VarChar 또는 Xml 이외의 가 사용되었습니다.

또는

이 로 SqlDbType 설정XmlReader되었을 때 ValueXml 이외의 가 사용되었습니다.

명령 텍스트를 실행하는 동안 발생한 오류입니다.

또는

스트리밍 작업 동안 시간이 초과되었습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

이름/값 쌍 "비동기 처리=true"가 이 SqlCommand에 대한 연결을 정의하는 연결 문자열 안에 포함되지 않았습니다.

또는

스트리밍 작업 동안 SqlConnection이 닫히거나 삭제되었습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

스트리밍 작업 동안 Stream, XmlReader 또는 TextReader 개체에서 오류가 발생했습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

스트리밍 작업 동안 Stream, XmlReader 또는 TextReader 개체가 닫혔습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

예제

다음 콘솔 애플리케이션 XML 데이터를 비동기적으로 검색 하는 프로세스를 시작 합니다. 결과 기다리는 동안이 간단한 애플리케이션 루프 상태를 조사 합니다 IsCompleted 속성 값입니다. 프로세스가 완료되면 코드는 XML을 검색하고 해당 내용을 표시합니다.

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";
    }
}
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

설명

메서드는 BeginExecuteXmlReader 문을 실행하는 동안 다른 작업을 동시에 실행할 수 있도록 행을 XML로 반환하는 Transact-SQL 문을 비동기적으로 실행하는 프로세스를 시작합니다. 문이 완료되면 개발자는 메서드를 EndExecuteXmlReader 호출하여 작업을 완료하고 명령에서 반환된 XML을 검색해야 합니다. 메서드는 BeginExecuteXmlReader 즉시 반환되지만 코드가 해당 EndExecuteXmlReader 메서드 호출을 실행할 때까지 동일한 SqlCommand 개체에 대해 동기 또는 비동기 실행을 시작하는 다른 호출을 실행해서는 안 됩니다. EndExecuteXmlReader 명령의 실행이 완료되기 전에 를 호출하면 실행이 SqlCommand 완료될 때까지 개체가 차단됩니다.

속성은 CommandText 일반적으로 유효한 FOR XML 절을 사용하여 Transact-SQL 문을 지정합니다. 그러나 는 CommandText 유효한 XML을 포함하는 데이터를 반환 ntext 하는 문을 지정할 수도 있습니다.

일반적인 BeginExecuteXmlReader 쿼리는 다음 C# 예제와 같이 형식을 지정할 수 있습니다.

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

이 메서드를 사용하여 단일 행, 단일 열 결과 집합을 검색할 수도 있습니다. 이 경우 둘 이상의 행이 반환 EndExecuteXmlReader 되면 메서드는 를 첫 번째 행의 값에 연결 XmlReader 하고 나머지 결과 집합을 삭제합니다.

MARS(다중 활성 결과 집합) 기능을 사용하면 여러 작업이 동일한 연결을 사용할 수 있습니다.

명령 텍스트와 매개 변수는 동기적으로 서버로 전송됩니다. 큰 명령 또는 많은 매개 변수가 전송되는 경우 이 메서드는 쓰기 중에 차단할 수 있습니다. 명령을 보낸 후 메서드는 서버에서 응답을 기다리지 않고 즉시 반환됩니다. 즉, 읽기는 비동기적입니다. 명령 실행은 비동기이지만 값 가져오기는 여전히 동기적입니다.

이 오버로드는 콜백 프로시저를 지원하지 않으므로 개발자는 메서드에서 반환된 의 속성을 사용하여 IsCompleted 명령이 완료되었는지 여부를 폴링하거나 반환IAsyncResultBeginExecuteXmlReader 의 속성을 사용하여 AsyncWaitHandle 하나 이상의 명령이 완료될 때까지 기다려야 IAsyncResult 합니다.

또는 BeginExecuteReader 를 사용하여 ExecuteReader XML 데이터에 액세스하는 경우 SQL Server 각각 2,033자의 여러 행에서 길이가 2,033자보다 큰 XML 결과를 반환합니다. 이 동작을 방지하려면 또는 BeginExecuteXmlReader 를 사용하여 ExecuteXmlReader FOR XML 쿼리를 읽습니다.

이 메서드는 속성을 무시합니다 CommandTimeout .

추가 정보

적용 대상

BeginExecuteXmlReader(AsyncCallback, Object)

콜백 프로시저를 사용하여 이 SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 결과를 XmlReader 개체로 반환합니다.

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

매개 변수

callback
AsyncCallback

명령의 실행이 완료되었을 때 호출되는 AsyncCallback 대리자입니다. 콜백이 필요하지 않도록 지정하려면 null(Microsoft Visual Basic에서는 Nothing)을 전달합니다.

stateObject
Object

콜백 프로시저에 전달된 사용자 정의 상태 개체입니다. AsyncState 속성을 사용하여 콜백 프로시저에서 이 개체를 검색합니다.

반환

결과를 폴링하거나 기다리는 데 사용하거나 두 작업을 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 명령의 결과를 XML로 반환하는 EndExecuteXmlReader(IAsyncResult)를 호출할 때도 이 값이 필요합니다.

예외

SqlDbType 로 설정된 Stream경우 ValueBinary 또는 VarBinary 이외의 가 사용되었습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

또는

이 로 SqlDbType 설정TextReader되었을 때 ValueChar, NChar, NVarChar, VarChar 또는 Xml 이외의 가 사용되었습니다.

또는

이 로 SqlDbType 설정XmlReader되었을 때 ValueXml 이외의 가 사용되었습니다.

명령 텍스트를 실행하는 동안 발생한 오류입니다.

또는

스트리밍 작업 동안 시간이 초과되었습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

이름/값 쌍 "비동기 처리=true"가 이 SqlCommand에 대한 연결을 정의하는 연결 문자열 안에 포함되지 않았습니다.

또는

스트리밍 작업 동안 SqlConnection이 닫히거나 삭제되었습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

스트리밍 작업 동안 Stream, XmlReader 또는 TextReader 개체에서 오류가 발생했습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

스트리밍 작업 동안 Stream, XmlReader 또는 TextReader 개체가 닫혔습니다. 스트리밍에 대한 자세한 내용은 SqlClient 스트리밍 지원을 참조하세요.

예제

다음 Windows 애플리케이션에서는 BeginExecuteXmlReader 메서드를 사용하여 몇 초의 지연이 포함된 Transact-SQL 문을 실행하는 방법을 보여 줍니다(장기 실행 명령을 에뮬레이션). 다음은 실행 중인 개체를 SqlCommand 매개 변수로 stateObject 전달하는 예제입니다. 이렇게 하면 코드가 에 대한 초기 호출에 해당하는 메서드를 호출 EndExecuteXmlReader 할 수 있도록 콜백 프로시저 내에서 개체를 간단하게 검색 SqlCommandBeginExecuteXmlReader수 있습니다.

이 예제에서는 많은 중요한 기술을 보여 줍니다. 여기에는 별도의 스레드에서 양식과 상호 작용하는 메서드 호출이 포함됩니다. 또한 이 예제에서는 사용자가 동시에 명령을 여러 번 실행하지 못하도록 차단해야 하는 방법과 콜백 프로시저가 호출되기 전에 폼이 닫히지 않도록 하는 방법을 보여 줍니다.

이 예제를 설정하려면 새 Windows 애플리케이션을 만듭니다. 폼에 Button 컨트롤, ListBox 컨트롤 및 컨트롤을 Label 배치합니다(각 컨트롤의 기본 이름 허용). 양식의 클래스에 다음 코드를 추가하여 필요에 따라 연결 문자열 수정합니다.

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

            // 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 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);
        }
    }
}
Imports System.Data.SqlClient
Imports System.Xml

Public Class Form1
    ' 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 Sub DisplayInfoDelegate(ByVal Text As String)
    Private Delegate Sub DisplayReaderDelegate(ByVal reader As XmlReader)

    Private isExecuting As Boolean

    ' This example maintains the connection object 
    ' externally, so that it is available for closing.
    Private connection As SqlConnection

    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

    Private Sub DisplayStatus(ByVal Text As String)
        Me.Label1.Text = Text
    End Sub

    Private Sub ClearProductInfo()
        ' Clear the list box.
        Me.ListBox1.Items.Clear()
    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
                Me.ListBox1.Items.Add(String.Format("{0}: {1:C}", _
                    reader("Name"), CSng(reader("ListPrice"))))
            End If
        End While
        DisplayStatus("Ready")
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If isExecuting Then
            MessageBox.Show(Me, "Cannot close the form until " & _
                "the pending asynchronous command has completed. Please wait...")
            e.Cancel = True
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        If isExecuting Then
            MessageBox.Show(Me, "Already executing. Please wait until the current query " & _
                "has completed.")
        Else
            Dim command As SqlCommand
            Try
                ClearProductInfo()
                DisplayStatus("Connecting...")
                connection = New SqlConnection(GetConnectionString())
                ' To emulate a long-running query, wait for 
                ' a few seconds before working with the data.
                Dim commandText As String = _
                    "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.
                Dim callback As New AsyncCallback(AddressOf HandleCallback)
                command.BeginExecuteXmlReader(callback, command)

            Catch ex As Exception
                isExecuting = False
                DisplayStatus(String.Format("Ready (last error: {0})", ex.Message))
                If connection IsNot Nothing Then
                    connection.Close()
                End If
            End Try
        End If
    End Sub

    Private Sub HandleCallback(ByVal result As IAsyncResult)
        Try
            ' Retrieve the original command object, passed
            ' to this procedure in the AsyncState property
            ' of the IAsyncResult parameter.
            Dim command As SqlCommand = CType(result.AsyncState, SqlCommand)
            Dim reader As XmlReader = 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. 
            Dim del As New DisplayReaderDelegate(AddressOf DisplayProductInfo)
            Me.Invoke(del, reader)

        Catch ex As Exception
            ' 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:
            Me.Invoke(New DisplayInfoDelegate(AddressOf DisplayStatus), _
                String.Format("Ready(last error: {0}", ex.Message))
        Finally
            isExecuting = False
            If connection IsNot Nothing Then
                connection.Close()
            End If
        End Try
    End Sub
End Class

설명

메서드는 BeginExecuteXmlReader 문을 실행하는 동안 다른 작업이 동시에 실행될 수 있도록 행을 XML로 반환하는 Transact-SQL 문 또는 저장 프로시저를 비동기적으로 실행하는 프로세스를 시작합니다. 문이 완료되면 개발자는 메서드를 EndExecuteXmlReader 호출하여 작업을 완료하고 요청된 XML 데이터를 검색해야 합니다. 메서드는 BeginExecuteXmlReader 즉시 반환되지만 코드가 해당 EndExecuteXmlReader 메서드 호출을 실행할 때까지 동일한 SqlCommand 개체에 대해 동기 또는 비동기 실행을 시작하는 다른 호출을 실행해서는 안 됩니다. EndExecuteXmlReader 명령의 실행이 완료되기 전에 를 호출하면 실행이 SqlCommand 완료될 때까지 개체가 차단됩니다.

속성은 CommandText 일반적으로 유효한 FOR XML 절을 사용하여 Transact-SQL 문을 지정합니다. 그러나 는 CommandText 유효한 XML을 포함하는 데이터를 반환하는 문을 지정할 수도 있습니다. 이 메서드를 사용하여 단일 행, 단일 열 결과 집합을 검색할 수도 있습니다. 이 경우 둘 이상의 행이 반환 EndExecuteXmlReader 되면 메서드는 를 첫 번째 행의 값에 연결 XmlReader 하고 나머지 결과 집합을 삭제합니다.

일반적인 BeginExecuteXmlReader 쿼리는 다음 C# 예제와 같이 형식을 지정할 수 있습니다.

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

이 메서드를 사용하여 단일 행, 단일 열 결과 집합을 검색할 수도 있습니다. 이 경우 둘 이상의 행이 반환 EndExecuteXmlReader 되면 메서드는 를 첫 번째 행의 값에 연결 XmlReader 하고 나머지 결과 집합을 삭제합니다.

MARS(다중 활성 결과 집합) 기능을 사용하면 여러 작업이 동일한 연결을 사용할 수 있습니다.

매개 변수를 callback 사용하면 문이 완료된 경우 호출되는 대리자를 지정할 AsyncCallback 수 있습니다. 호출할 수 있습니다는 EndExecuteXmlReader 메서드에서이 대리자 프로시저 내에서 또는 애플리케이션 내에서 다른 위치에서. 또한 매개 변수의 stateObject 개체를 전달할 수 있으며 콜백 프로시저는 속성을 사용하여 이 정보를 검색할 AsyncState 수 있습니다.

명령 텍스트와 매개 변수는 동기적으로 서버로 전송됩니다. 큰 명령 또는 많은 매개 변수가 전송되는 경우 이 메서드는 쓰기 중에 차단할 수 있습니다. 명령을 보낸 후 메서드는 서버에서 응답을 기다리지 않고 즉시 반환됩니다. 즉, 읽기는 비동기적입니다.

작업을 실행하는 동안 발생하는 모든 오류는 콜백 프로시저에서 예외로 throw됩니다. 주 애플리케이션이 아니라 콜백 프로시저에서 예외를 처리 해야 합니다. 콜백 프로시저의 예외 처리에 대한 자세한 내용은 이 항목의 예제를 참조하세요.

또는 BeginExecuteReader 를 사용하여 ExecuteReader XML 데이터에 액세스하는 경우 SQL Server 각각 2,033자의 여러 행에서 길이가 2,033자보다 큰 XML 결과를 반환합니다. 이 동작을 방지하려면 또는 BeginExecuteXmlReader 를 사용하여 ExecuteXmlReader FOR XML 쿼리를 읽습니다.

이 메서드는 속성을 무시합니다 CommandTimeout .

추가 정보

적용 대상