Share via


SqlCommand.BeginExecuteXmlReader 메서드

정의

오버로드

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 결과를 폴링하거나 대기하는 데 사용할 수 있는 입니다. 호출할 때도 이 값이 필요합니다.EndExecuteXmlReader 단일 XML 값을 반환하는 입니다.

예외

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

또는

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

또는

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

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

또는

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

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

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

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

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

예제

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

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

설명

메서드는 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 ( Nothing Microsoft Visual Basic의 경우) 콜백이 필요하지 않음을 나타냅니다.

stateObject
Object

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

반환

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

예외

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

또는

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

또는

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

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

또는

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

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

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

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

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

예제

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

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

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

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

설명

메서드는 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 .

추가 정보

적용 대상