SqlCommand.BeginExecuteReader 메서드

정의

SqlCommand에서 설명하는 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 서버에서 하나 이상의 결과 집합을 검색합니다.

오버로드

BeginExecuteReader()

SqlCommand에서 설명하는 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 서버에서 하나 이상의 결과 집합을 검색합니다.

BeginExecuteReader(CommandBehavior)

CommandBehavior 값 중 하나를 사용하여 이 SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작합니다.

BeginExecuteReader(AsyncCallback, Object)

콜백 프로시저와 상태 정보가 주어진 상태에서 이 SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 서버에서 하나 이상의 결과 집합을 검색합니다.

BeginExecuteReader(AsyncCallback, Object, CommandBehavior)

콜백 프로시저와 상태 정보가 주어진 상태에서 이 SqlCommand에서 설명하는 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 CommandBehavior 값 중 하나를 사용하여 서버에서 결과 집합을 하나 이상 검색합니다.

BeginExecuteReader()

SqlCommand에서 설명하는 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 서버에서 하나 이상의 결과 집합을 검색합니다.

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

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 반환된 행을 검색하는 데 사용할 수 있는 SqlDataReader 인스턴스를 반환하는 EndExecuteReader(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 스트리밍 지원을 참조하세요.

예제

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

using System.Data.SqlClient;

class Class1
{
    static void Main()
    {
        // This is a simple example that demonstrates the usage of the
        // BeginExecuteReader functionality
        // The WAITFOR statement simply adds enough time to prove the
        // asynchronous nature of the command.
        string commandText =
            "WAITFOR DELAY '00:00:03';" +
            "SELECT LastName, FirstName FROM Person.Contact " +
            "WHERE LastName LIKE 'M%'";

        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))
        {
            try
            {
                SqlCommand command = new SqlCommand(commandText, connection);

                connection.Open();
                IAsyncResult result = command.BeginExecuteReader();

                // Although it is not necessary, the following code
                // 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)
                {
                    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.
                    System.Threading.Thread.Sleep(100);
                }

                using (SqlDataReader reader = command.EndExecuteReader(result))
                {
                    DisplayResults(reader);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                // You might want to pass these errors
                // back out to the caller.
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
    }

    private static void DisplayResults(SqlDataReader reader)
    {
        // Display the data within the reader.
        while (reader.Read())
        {
            // Display all the columns.
            for (int i = 0; i < reader.FieldCount; i++)
                Console.Write("{0} ", reader.GetValue(i));
            Console.WriteLine();
        }
    }

    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

Module Module1
    Sub Main()
        ' This is a simple example that demonstrates the usage of the 
        ' BeginExecuteReader functionality.
        ' 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 LastName, FirstName FROM Person.Contact " & _
         "WHERE LastName LIKE 'M%'"

        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.BeginExecuteReader()

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

                ' Once the IAsyncResult object signals that it is done
                ' waiting for results, you can retrieve the results.
                Using reader As SqlDataReader = command.EndExecuteReader(result)
                    DisplayResults(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 DisplayResults(ByVal reader As SqlDataReader)
        ' Display the data within the reader.
        While reader.Read()
            ' Display all the columns.
            For i As Integer = 0 To reader.FieldCount - 1
                Console.Write("{0} ", reader.GetValue(i))
            Next
            Console.WriteLine()
        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

설명

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

명령 텍스트와 매개 변수는 동기적으로 서버로 전송됩니다. 큰 명령 또는 많은 매개 변수가 전송되는 경우 이 메서드는 쓰기 중에 차단할 수 있습니다. 명령을 보낸 후 메서드는 서버에서 응답을 기다리지 않고 즉시 반환됩니다. 즉, 읽기는 비동기적입니다. 명령 실행은 비동기이지만 값 가져오기는 여전히 동기적입니다. 즉, 에 대한 Read 호출은 더 많은 데이터가 필요하고 기본 네트워크의 읽기 작업 블록이 필요한 경우 차단할 수 있습니다.

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

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

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

추가 정보

적용 대상

BeginExecuteReader(CommandBehavior)

CommandBehavior 값 중 하나를 사용하여 이 SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작합니다.

public:
 IAsyncResult ^ BeginExecuteReader(System::Data::CommandBehavior behavior);
public IAsyncResult BeginExecuteReader (System.Data.CommandBehavior behavior);
member this.BeginExecuteReader : System.Data.CommandBehavior -> IAsyncResult
Public Function BeginExecuteReader (behavior As CommandBehavior) As IAsyncResult

매개 변수

behavior
CommandBehavior

문 실행 및 데이터 검색 옵션을 나타내는 CommandBehavior 값 중 하나입니다.

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 반환된 행을 검색하는 데 사용할 수 있는 SqlDataReader 인스턴스를 반환하는 EndExecuteReader(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 스트리밍 지원을 참조하세요.

예제

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

또한 이 예제에서는 동작 매개 변수의 CommandBehavior.CloseConnectionCommandBehavior.SingleRow 값을 전달하여 반환 SqlDataReader 된 가 닫혀 연결이 닫혀 단일 행 결과에 최적화되도록 합니다.

using System.Data.SqlClient;
class Class1
{
    static void Main()
    {
        // This example is not terribly useful, 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 ProductID, Name FROM Production.Product WHERE ListPrice < 100";

        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.

        try
        {
            // The code does not need to handle closing the connection explicitly--
            // the use of the CommandBehavior.CloseConnection option takes care
            // of that for you.
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand(commandText, connection);

            connection.Open();
            IAsyncResult result = command.BeginExecuteReader(
                CommandBehavior.CloseConnection);

            // Although it is not necessary, the following code
            // 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);
            }

            using (SqlDataReader reader = command.EndExecuteReader(result))
            {
                DisplayResults(reader);
            }
        }
        catch (SqlException ex)
        {
            Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Error: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            // You might want to pass these errors
            // back out to the caller.
            Console.WriteLine("Error: {0}", ex.Message);
        }
    }

    private static void DisplayResults(SqlDataReader reader)
    {
        // Display the data within the reader.
        while (reader.Read())
        {
            // Display all the columns.
            for (int i = 0; i < reader.FieldCount; i++)
            {
                Console.Write("{0}\t", reader.GetValue(i));
            }
            Console.WriteLine();
        }
    }

    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

Module Module1
    Sub Main()
        ' This example is not terribly useful, 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 ProductID, Name FROM Production.Product WHERE ListPrice < 100"

        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. 
        Try
            ' The code does not need to handle closing the connection explicitly--
            ' the use of the CommandBehavior.CloseConnection option takes care
            ' of that for you. 
            Dim connection As New SqlConnection(connectionString)
            Dim command As New SqlCommand(commandText, connection)

            connection.Open()
            Dim result As IAsyncResult = _
              command.BeginExecuteReader(CommandBehavior.CloseConnection)

            ' Although it is not necessary, the following code
            ' 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

            ' The "using" statement closes the SqlDataReader when it is 
            ' done executing.
            Using reader As SqlDataReader = command.EndExecuteReader(result)
                DisplayResults(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 Sub

    Private Sub DisplayResults(ByVal reader As SqlDataReader)
        ' Display the data within the reader.
        While reader.Read()
            ' Display all the columns. 
            For i As Integer = 0 To reader.FieldCount - 1
                Console.Write("{0} ", reader.GetValue(i))
            Next
            Console.WriteLine()
        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

설명

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

매개 변수를 behavior 사용하면 명령 및 해당 연결의 동작을 제어하는 옵션을 지정할 수 있습니다. 이러한 값은 프로그래밍 언어 연 OR 산자를 사용하여 함께 결합할 수 있습니다. 일반적으로 개발자는 값을 사용하여 CommandBehavior.CloseConnection 가 닫혀 있을 때 SqlDataReader 런타임에 의해 연결이 닫혀 있는지 확인합니다.

명령 텍스트와 매개 변수는 동기적으로 서버로 전송됩니다. 큰 명령 또는 많은 매개 변수가 전송되는 경우 이 메서드는 쓰기 중에 차단할 수 있습니다. 명령을 보낸 후 메서드는 서버에서 응답을 기다리지 않고 즉시 반환됩니다. 즉, 읽기는 비동기적입니다. 명령 실행은 비동기이지만 값 가져오기는 여전히 동기적입니다. 즉, 에 대한 Read 호출은 더 많은 데이터가 필요하고 기본 네트워크의 읽기 작업 블록이 필요한 경우 차단할 수 있습니다.

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

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

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

추가 정보

적용 대상

BeginExecuteReader(AsyncCallback, Object)

콜백 프로시저와 상태 정보가 주어진 상태에서 이 SqlCommand에서 설명한 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 서버에서 하나 이상의 결과 집합을 검색합니다.

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

매개 변수

callback
AsyncCallback

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

stateObject
Object

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

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 반환된 행을 검색하는 데 사용할 수 있는 SqlDataReader 인스턴스를 반환하는 EndExecuteReader(IAsyncResult)를 호출할 때도 이 값이 필요합니다.

예외

SqlDbType 또는 VarBinary 이외의 는 로 설정Stream되었을 때 Value 사용되었습니다. 스트리밍에 대한 자세한 내용은 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 애플리케이션에서는 BeginExecuteReader 메서드를 사용하여 몇 초의 지연이 포함된 Transact-SQL 문을 실행하는 방법을 보여 줍니다(장기 실행 명령을 에뮬레이션). 샘플은 명령을 비동기적으로 실행하므로 결과를 기다리는 동안 양식이 응답성을 유지합니다. 이 예제에서는 실행 중인 개체를 SqlCommand 매개 변수로 stateObject 전달합니다. 이렇게 하면 콜백 프로시저 내에서 개체를 간단하게 검색 SqlCommand 할 수 있으므로 코드에서 에 대한 초기 호출BeginExecuteReader에 해당하는 메서드를 호출 EndExecuteReader 할 수 있습니다.

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

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

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

Public Class Form1
    ' 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 Sub FillGridDelegate(ByVal reader As SqlDataReader)

    ' You need this delegate to update the status bar.
    Private Delegate Sub DisplayStatusDelegate(ByVal Text As String)

    ' This flag ensures that the user does not attempt
    ' to restart the command or close the form while the 
    ' asynchronous command is executing.
    Private isExecuting As Boolean

    ' 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 connection As SqlConnection

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

    Private Sub FillGrid(ByVal reader As SqlDataReader)
        Try
            Dim table As New DataTable
            table.Load(reader)
            Me.DataGridView1.DataSource = table
            DisplayStatus("Ready")

        Catch ex As Exception
            ' 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 Not reader Is Nothing Then
                reader.Close()
            End If
            If Not connection Is Nothing Then
                connection.Close()
            End If
        End Try
    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 SqlDataReader = 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. 
            Dim del As New FillGridDelegate(AddressOf FillGrid)
            Me.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 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 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:
            Me.Invoke(New DisplayStatusDelegate(AddressOf DisplayStatus), _
             "Error: " & ex.Message)
        Finally
            isExecuting = False
        End Try
    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 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"
    End Function

    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
                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.
                Dim callback As New AsyncCallback(AddressOf HandleCallback)
                command.BeginExecuteReader(callback, command)

            Catch ex As Exception
                DisplayStatus("Error: " & ex.Message)
                If connection IsNot Nothing Then
                    connection.Close()
                End If
            End Try
        End If
    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
End Class

설명

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

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

명령 텍스트 및 매개 변수는 동기적으로 서버로 전송됩니다. 큰 명령 또는 많은 매개 변수가 전송되는 경우 이 메서드는 쓰기 중에 차단할 수 있습니다. 명령을 보낸 후 메서드는 서버에서 응답을 기다리지 않고 즉시 반환됩니다. 즉, 읽기는 비동기적입니다. 명령 실행은 비동기이지만 값 가져오기는 여전히 동기적입니다. 즉, 더 많은 데이터가 필요하고 기본 네트워크의 읽기 작업 블록이 있는 경우 에 대한 호출 Read 이 차단할 수 있습니다.

콜백 프로시저에서 Microsoft.NET 런타임에서 제공 되는 백그라운드 스레드에서 실행 되므로 애플리케이션 내에서 스레드 간 상호 작용을 처리 하는 엄격한 접근 방식을 수행 하는 것이 중요 합니다. 예를 들어 콜백 프로시저 내에서 양식의 내용과 상호 작용해서는 안 됩니다. 양식을 업데이트해야 하는 경우 작업을 수행하려면 폼의 스레드로 다시 전환해야 합니다. 이 항목의 예제에서는 이 동작을 보여 줍니다.

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

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

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

추가 정보

적용 대상

BeginExecuteReader(AsyncCallback, Object, CommandBehavior)

콜백 프로시저와 상태 정보가 주어진 상태에서 이 SqlCommand에서 설명하는 Transact-SQL 문이나 저장 프로시저의 비동기 실행을 시작하고 CommandBehavior 값 중 하나를 사용하여 서버에서 결과 집합을 하나 이상 검색합니다.

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

매개 변수

callback
AsyncCallback

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

stateObject
Object

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

behavior
CommandBehavior

문 실행 및 데이터 검색 옵션을 나타내는 CommandBehavior 값 중 하나입니다.

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 반환된 행을 검색하는 데 사용할 수 있는 SqlDataReader 인스턴스를 반환하는 EndExecuteReader(IAsyncResult)를 호출할 때도 이 값이 필요합니다.

예외

SqlDbType 또는 VarBinary 이외의 는 로 설정Stream되었을 때 Value 사용되었습니다. 스트리밍에 대한 자세한 내용은 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 애플리케이션에서는 BeginExecuteReader 메서드를 사용하여 몇 초의 지연이 포함된 Transact-SQL 문을 실행하는 방법을 보여 줍니다(장기 실행 명령을 에뮬레이션). 샘플은 명령을 비동기적으로 실행하므로 결과를 기다리는 동안 폼이 응답성을 유지합니다. 이 예제에서는 실행 중인 개체를 SqlCommand 매개 변수로 stateObject 전달합니다. 이렇게 하면 콜백 프로시저 내에서 개체를 간단하게 검색 SqlCommand 할 수 있으므로 코드가 에 대한 초기 호출BeginExecuteReader에 해당하는 메서드를 호출 EndExecuteReader 할 수 있습니다.

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

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

이 예제에서는 매개 변수의 CommandBehavior.CloseConnection 값을 behavior 전달하여 반환 SqlDataReader 된 가 닫히면 자동으로 연결을 닫습니다.

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;

        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
            {
                // Closing the reader also closes the connection,
                // because this reader was created using the
                // CommandBehavior.CloseConnection value.
                if (reader != null)
                {
                    reader.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;
                SqlConnection connection = 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,
                        CommandBehavior.CloseConnection);
                }
                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;
            }
        }
    }
}
Imports System.Data.SqlClient

Public Class Form1
    ' Add this code to the form's class:
    ' You 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 Sub FillGridDelegate(ByVal reader As SqlDataReader)

    ' You need this delegate to update the status bar.
    Private Delegate Sub DisplayStatusDelegate(ByVal Text As String)

    ' This flag ensures that the user does not attempt
    ' to restart the command or close the form while the 
    ' asynchronous command is executing.
    Private isExecuting As Boolean

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

    Private Sub FillGrid(ByVal reader As SqlDataReader)
        Try
            Dim table As New DataTable
            table.Load(reader)
            Me.DataGridView1.DataSource = table
            DisplayStatus("Ready")

        Catch ex As Exception
            ' 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
            ' Closing the reader also closes the connection,
            ' because this reader was created using the 
            ' CommandBehavior.CloseConnection value.
            If reader IsNot Nothing Then
                reader.Close()
            End If
        End Try
    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 SqlDataReader = 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. 
            Dim del As New FillGridDelegate(AddressOf FillGrid)
            Me.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 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 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:
            Me.Invoke(New DisplayStatusDelegate(AddressOf DisplayStatus), _
             "Error: " & ex.Message)
        Finally
            isExecuting = False
        End Try
    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 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"
    End Function

    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 connection As SqlConnection
            Dim command As SqlCommand
            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.
                Dim callback As New AsyncCallback(AddressOf HandleCallback)
                command.BeginExecuteReader(callback, command, _
                  CommandBehavior.CloseConnection)

            Catch ex As Exception
                DisplayStatus("Error: " & ex.Message)
                If connection IsNot Nothing Then
                    connection.Close()
                End If
            End Try
        End If
    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
End Class

설명

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

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

매개 변수를 behavior 사용하면 명령 및 해당 연결의 동작을 제어하는 옵션을 지정할 수 있습니다. 이러한 값은 프로그래밍 언어의 Or 연산자를 사용하여 함께 결합할 수 있습니다. 일반적으로 개발자는 이 값을 사용하여 CloseConnection 가 닫혔을 때 SqlDataReader 런타임에 의해 연결이 닫히도록 합니다. 또한 개발자는 Transact-SQL 문 또는 저장 프로시저가 단일 행만 반환한다는 것을 미리 알 때 값을 지정하여 SingleRow 의 동작 SqlDataReader 을 최적화할 수 있습니다.

명령 텍스트 및 매개 변수는 동기적으로 서버로 전송됩니다. 큰 명령 또는 많은 매개 변수가 전송되는 경우 이 메서드는 쓰기 중에 차단할 수 있습니다. 명령을 보낸 후 메서드는 서버에서 응답을 기다리지 않고 즉시 반환됩니다. 즉, 읽기는 비동기적입니다. 명령 실행은 비동기이지만 값 가져오기는 여전히 동기적입니다. 즉, 더 많은 데이터가 필요하고 기본 네트워크의 읽기 작업 블록이 있는 경우 에 대한 호출 Read 이 차단할 수 있습니다.

콜백 프로시저에서 Microsoft.NET 공용 언어 런타임에서 제공 되는 백그라운드 스레드에서 실행 되므로 애플리케이션 내에서 스레드 간 상호 작용을 처리 하는 엄격한 접근 방식을 수행 하는 것이 중요 합니다. 예를 들어 콜백 프로시저 내에서 양식의 내용과 상호 작용해서는 안 됩니다. 양식을 업데이트해야 하는 경우 작업을 수행하려면 폼의 스레드로 다시 전환해야 합니다. 이 항목의 예제에서는 이 동작을 보여 줍니다.

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

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

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

추가 정보

적용 대상