本文為機器翻譯文章。如需檢視英文版,請選取 [原文] 核取方塊。您也可以將滑鼠指標移到文字上,即可在快顯視窗顯示英文原文。
譯文
原文

SqlCommand.BeginExecuteReader 方法 ()

 

起始這個 SqlCommand 所描述之 Transact-SQL 陳述式或預存程序的非同步執行,並從伺服器擷取一或多個結果集。

命名空間:   System.Data.SqlClient
組件:  System.Data (於 System.Data.dll)

[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public IAsyncResult BeginExecuteReader()

傳回值

Type: System.IAsyncResult

IAsyncResult,可用於輪詢或等待結果 (或兩者);叫用 EndExecuteReader 以傳回可用以擷取所傳回資料列的 SqlDataReader 執行個體時,也需要這個值。

Exception Condition
InvalidCastException

Value 設定為 Stream 時,使用了 BinaryVarBinary 以外的 SqlDbType 如需有關資料流處理的詳細資訊,請參閱 SqlClient 資料流支援

Value 設定為 TextReader 時,使用了 CharNCharNVarCharVarCharXml 以外的 SqlDbType

Value 設定為 XmlReader 時,使用了 Xml 以外的 SqlDbType

SqlException

執行命令文字時發生的任何錯誤。

串流作業期間發生逾時。 如需有關資料流處理的詳細資訊,請參閱 SqlClient 資料流支援

InvalidOperationException

定義這個 SqlCommand 之連接的連接字串中未包含名稱/值組 "Asynchronous Processing=true"。

在串流作業期間已關閉或卸除的 SqlConnection 如需有關資料流處理的詳細資訊,請參閱 SqlClient 資料流支援

IOException

StreamXmlReaderTextReader 物件在串流作業期間發生錯誤。 如需有關資料流處理的詳細資訊,請參閱 SqlClient 資料流支援

ObjectDisposedException

StreamXmlReaderTextReader 物件在串流作業期間已關閉。 如需有關資料流處理的詳細資訊,請參閱 SqlClient 資料流支援

The M:System.Data.SqlClient.SqlCommand.BeginExecuteReader method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the M:System.Data.SqlClient.SqlCommand.EndExecuteReader(System.IAsyncResult) method to finish the operation and retrieve the T:System.Data.SqlClient.SqlDataReader returned by the command. The M:System.Data.SqlClient.SqlCommand.BeginExecuteReader method returns immediately, but until the code executes the corresponding M:System.Data.SqlClient.SqlCommand.EndExecuteReader(System.IAsyncResult) method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same T:System.Data.SqlClient.SqlCommand object. Calling the M:System.Data.SqlClient.SqlCommand.EndExecuteReader(System.IAsyncResult) before the command's execution is completed causes the T:System.Data.SqlClient.SqlCommand object to block until the execution is finished.

Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to M:System.Data.SqlClient.SqlDataReader.Read may block if more data is required and the underlying network's read operation blocks.

Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the P:System.IAsyncResult.IsCompleted property of the T:System.IAsyncResult returned by the M:System.Data.SqlClient.SqlCommand.BeginExecuteReader method; or wait for the completion of one or more commands using the P:System.IAsyncResult.AsyncWaitHandle property of the returned T:System.IAsyncResult.

If you use M:System.Data.SqlClient.SqlCommand.ExecuteReader or M:System.Data.SqlClient.SqlCommand.BeginExecuteReader to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use M:System.Data.SqlClient.SqlCommand.ExecuteXmlReader or Overload:System.Data.SqlClient.SqlCommand.BeginExecuteXmlReader to read FOR XML queries. For more information, see article Q310378, "PRB: XML Data Is Truncated When You Use SqlDataReader," in the Microsoft Knowledge Base at http://support.microsoft.com.

The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the P:System.IAsyncResult.IsCompleted property value. As soon as the process has completed, the code retrieves the T:System.Data.SqlClient.SqlDataReader and displays its contents.

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

.NET Framework
自 2.0 起供應
回到頁首
顯示: