다음을 통해 공유


SqlConnectionStringBuilder.AsynchronousProcessing 속성

정의

이 연결 문자열을 사용하여 만든 연결에서 비동기 처리를 허용하는지 여부를 나타내는 부울 값을 가져오거나 설정합니다.

public:
 property bool AsynchronousProcessing { bool get(); void set(bool value); };
public bool AsynchronousProcessing { get; set; }
member this.AsynchronousProcessing : bool with get, set
Public Property AsynchronousProcessing As Boolean

속성 값

AsynchronousProcessing 속성의 값이거나, 제공된 값이 없으면 false입니다.

예제

다음 예제에서는 연결 문자열을 검색하고 연결 문자열이 비동기 처리를 허용하도록 구성되었는지 확인합니다. 이 경우 연결 문자열이 애플리케이션 내의 프로시저에서 제공되지만 프로덕션 애플리케이션에서는 연결 문자열이 구성 파일이나 다른 소스에서 제공될 수도 있습니다. 그런 다음 이 예제에서는 비동기 작업을 수행하여 백그라운드 스레드에서 샘플 데이터베이스 내의 값을 업데이트합니다.

using System.Data.SqlClient;
using System.Threading;

class Program
{
    static void Main()
    {
        // Create a SqlConnectionStringBuilder instance,
        // and ensure that it is set up for asynchronous processing.
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(GetConnectionString());
        // Asynchronous method calls won't work unless you
        // have added this option, or have added
        // the clause "Asynchronous Processing=true"
        // to the connection string.
        builder.AsynchronousProcessing = true;

        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, builder.ConnectionString);

        Console.WriteLine("Press any key to finish.");
        Console.ReadLine();
    }

    private static 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=SSPI;" +
            "Initial Catalog=AdventureWorks";
    }

    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's 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
                    // doesn't consume all available resources
                    // on the main thread.
                    Thread.Sleep(100);
                    count += 1;
                }
                Console.WriteLine("Command complete. Affected {0} rows.",
                    command.EndExecuteNonQuery(result));
            }
            catch (SqlException ex)
            {
                Console.WriteLine(
                    "Error {0}: System.Data.SqlClient.SqlConnectionStringBuilder",
                    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);
            }
        }
    }
}
Imports System.Data.SqlClient
Imports System.Threading


Module Module1
    Sub Main()
        ' Create a SqlConnectionStringBuilder instance, 
        ' and ensure that it is set up for asynchronous processing.
        Dim builder As _
         New SqlConnectionStringBuilder(GetConnectionString())
        ' Asynchronous method calls won't work unless you
        ' have added this option, or have added
        ' the clause "Asynchronous Processing=True"
        ' to the connection string.
        builder.AsynchronousProcessing = True

        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, builder.ConnectionString)

        Console.WriteLine("Press any key to finish.")
        Console.ReadLine()
    End Sub

    Private Function GetConnectionString() As String
        ' To avoid storing the connection string in your code,
        ' you can retrieve it from a configuration file. 
        Return "Data Source=(local);Integrated Security=SSPI;" & _
          "Initial Catalog=AdventureWorks"
    End Function

    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's 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
                    ' doesn't 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}: System.Data.SqlClient.SqlConnectionStringBuilder", _
                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
End Module

설명

이 속성은 연결 문자열 내의 "Asynchronous Processing" 및 "async" 키에 해당합니다. SqlCommand 개체에서 제공하는 비동기 처리의 이점을 얻으려면 이 키/값 쌍이 연결된 SqlConnection 개체의 연결 문자열 내에 포함되어야 합니다.

적용 대상

추가 정보