SqlCommand.BeginExecuteNonQuery 메서드

정의

SqlCommand가 설명하는 저장 프로시저 또는 Transact-SQL 문의 비동기 실행을 시작합니다.

오버로드

BeginExecuteNonQuery()

SqlCommand가 설명하는 저장 프로시저 또는 Transact-SQL 문의 비동기 실행을 시작합니다.

BeginExecuteNonQuery(AsyncCallback, Object)

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

BeginExecuteNonQuery()

SqlCommand가 설명하는 저장 프로시저 또는 Transact-SQL 문의 비동기 실행을 시작합니다.

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

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 이 값은 영향을 받는 행의 수를 반환하는 EndExecuteNonQuery(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 스트리밍 지원을 참조하세요.

예제

다음 콘솔 애플리케이션에서는 합니다 AdventureWorks 샘플 데이터베이스에서 해당 작업을 비동기적으로 수행 합니다. 이 예제에서는 장기 실행 프로세스를 에뮬레이트할 수 있도록 명령 텍스트에 WAITFOR 문을 삽입합니다. 일반적으로 명령을 느리게 실행하기 위해 노력하지는 않지만 이 경우 이 작업을 수행하면 비동기 동작을 더 쉽게 보여줄 수 있습니다.

using System.Data.SqlClient;

class Class1
{
    static void Main()
    {
        // This is a simple example that demonstrates the usage of the
        // BeginExecuteNonQuery functionality.
        // The WAITFOR statement simply adds enough time to prove the
        // asynchronous nature of the command.

        string commandText =
            "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " +
            "WHERE ReorderPoint Is Not Null;" +
            "WAITFOR DELAY '0:0:3';" +
            "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " +
            "WHERE ReorderPoint Is Not Null";

        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
            {
                int count = 0;
                SqlCommand command = new SqlCommand(commandText, connection);
                connection.Open();

                IAsyncResult result = command.BeginExecuteNonQuery();
                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);
                }
                Console.WriteLine("Command complete. Affected {0} rows.",
                    command.EndExecuteNonQuery(result));
            }
            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 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=SSPI;" +
            "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 
        ' BeginExecuteNonQuery functionality.
        ' The WAITFOR statement simply adds enough time to prove the 
        ' asynchronous nature of the command.
        Dim commandText As String = _
         "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " & _
         "WHERE ReorderPoint Is Not Null;" & _
         "WAITFOR DELAY '0:0:3';" & _
         "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " & _
         "WHERE ReorderPoint Is Not Null"

        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 count As Integer = 0
                Dim command As New SqlCommand(commandText, connection)
                connection.Open()
                Dim result As IAsyncResult = command.BeginExecuteNonQuery()
                While Not 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.
                    Threading.Thread.Sleep(100)
                    count += 1
                End While
                Console.WriteLine("Command complete. Affected {0} rows.", _
                    command.EndExecuteNonQuery(result))
            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 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=SSPI;" & _
          "Initial Catalog=AdventureWorks; Asynchronous Processing=true"
    End Function
End Module

설명

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

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

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

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

추가 정보

적용 대상

BeginExecuteNonQuery(AsyncCallback, Object)

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

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

매개 변수

callback
AsyncCallback

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

stateObject
Object

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

반환

결과를 폴링하거나 기다리는 데 사용하거나 또는 두 작업 모두 수행하는 데 사용할 수 있는 IAsyncResult이며, 이 값은 영향을 받는 행의 수를 반환하는 EndExecuteNonQuery(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 애플리케이션의 사용을 보여 줍니다.는 BeginExecuteNonQuery 메서드, (장기 실행 명령을 에뮬레이션) 몇 초 간의 지연이 포함 하는 TRANSACT-SQL 문을 실행 합니다.

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

이 예제를 설정하려면 새 Windows 애플리케이션을 만듭니다. 폼에 Button 컨트롤과 컨트롤을 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:
        private void Form1_Load(object sender, EventArgs e)
        {
            this.button1.Click += new System.EventHandler(this.button1_Click);
            this.FormClosing += new System.Windows.Forms.
                FormClosingEventHandler(this.Form1_FormClosing);
        }

        // You need this delegate in order to display text from a thread
        // other than the form's thread. See the HandleCallback
        // procedure for more information.
        // This same delegate matches both the DisplayStatus
        // and DisplayResults methods.
        private delegate void DisplayInfoDelegate(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;

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

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

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

        private void DisplayResults(string Text)
        {
            this.label1.Text = Text;
            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
                {
                    DisplayResults("");
                    DisplayStatus("Connecting...");
                    connection = new SqlConnection(GetConnectionString());
                    // To emulate a long-running query, wait for
                    // a few seconds before working with the data.
                    // This command does not do much, but that's the point--
                    // it does not change your data, in the long run.
                    string commandText =
                        "WAITFOR DELAY '0:0:05';" +
                        "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " +
                        "WHERE ReorderPoint Is Not Null;" +
                        "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " +
                        "WHERE ReorderPoint Is Not Null";

                    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
                    // BeginExecuteNonQuery call, doing so makes it easier
                    // to call EndExecuteNonQuery in the callback procedure.
                    AsyncCallback callback = new AsyncCallback(HandleCallback);
                    command.BeginExecuteNonQuery(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;
                int rowCount = command.EndExecuteNonQuery(result);
                string rowText = " rows affected.";
                if (rowCount == 1)
                {
                    rowText = " row affected.";
                }
                rowText = rowCount + rowText;

                // 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
                // displays the results, like this:
                // DisplayResults(rowText)

                // 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.
                DisplayInfoDelegate del = new DisplayInfoDelegate(DisplayResults);
                this.Invoke(del, rowText);
            }
            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();
                }
            }
        }
    }
}
Imports System.Data.SqlClient

Public Class Form1
    ' Add this code to the form's class:
    ' You need this delegate in order to display text from a thread
    ' other than the form's thread. See the HandleCallback
    ' procedure for more information.
    ' This same delegate matches both the DisplayStatus 
    ' and DisplayResults methods.
    Private Delegate Sub DisplayInfoDelegate(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

    ' 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 DisplayResults(ByVal Text As String)
        Me.Label1.Text = Text
        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
                DisplayResults("")
                DisplayStatus("Connecting...")
                connection = New SqlConnection(GetConnectionString())
                ' To emulate a long-running query, wait for 
                ' a few seconds before working with the data.
                ' This command does not do much, but that's the point--
                ' it does not change your data, in the long run.
                Dim commandText As String = _
                    "WAITFOR DELAY '0:0:05';" & _
                    "UPDATE Production.Product SET ReorderPoint = ReorderPoint + 1 " & _
                    "WHERE ReorderPoint Is Not Null;" & _
                    "UPDATE Production.Product SET ReorderPoint = ReorderPoint - 1 " & _
                    "WHERE ReorderPoint Is Not Null"

                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 
                ' BeginExecuteNonQuery call, doing so makes it easier
                ' to call EndExecuteNonQuery in the callback procedure.
                Dim callback As New AsyncCallback(AddressOf HandleCallback)
                command.BeginExecuteNonQuery(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 rowCount As Integer = command.EndExecuteNonQuery(result)
            Dim rowText As String = " rows affected."
            If rowCount = 1 Then
                rowText = " row affected."
            End If
            rowText = rowCount & rowText

            ' 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 
            ' displays the results, like this:
            ' DisplayResults(rowText)

            ' 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 DisplayInfoDelegate(AddressOf DisplayResults)
            Me.Invoke(del, rowText)

        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

설명

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

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

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

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

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

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

추가 정보

적용 대상