Accessing Data Asynchronously

One of the biggest problems with ADO.NET in previous versions is that no matter how responsive your application was, everything still had to wait for a command to execute. In other words, all command executions were done synchronously, whether the command took .2 or 200 seconds to execute.

Most developers got around this by wrapping the command execution in a method that was spawned in a background thread to allow the execution to take place while the rest of the application remained responsive.

With ADO.NET 2.0, that workaround is no longer necessary. You can use the standard Begin/End asynchronous method pattern that is prevalent throughout the .NET Framework. The SqlCommand class now has a corresponding Begin/End pair for some of its execute methods: ExecuteNonQuery(), ExecuteReader(), and ExecuteXmlReader().

Using these new methods, you can initiate an asynchronous command and then continue responding to events from the rest of the application. When the results are available, they will be returned to your application using one of the appropriate End methods, as shown in Listing 18.3.

Listing 18.3. Asynchronous Command Execution

[View full width]

using System; using System.Threading; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Text; namespace AsyncCommandDemo { class Program { static void Main(string[] args) {     SqlConnection conn = new SqlConnection(         "data source=localhost; initial catalog=SampleDB; Integrated  Security=SSPI;Asynchronous Processing=true;");     conn.Open();     SqlCommand cmd = conn.CreateCommand();     cmd.CommandText = "SELECT * FROM Customers";     cmd.BeginExecuteReader(new AsyncCallback(ExecuteAsync), cmd);     Console.WriteLine("Asynchronous execution of command has begun...");     Console.ReadLine(); } public static void ExecuteAsync(IAsyncResult ar) {     Thread.Sleep(3000); // simulate a longer query     SqlCommand originalCommand = (SqlCommand)ar.AsyncState;     SqlDataReader dr = originalCommand.EndExecuteReader(ar);     while (dr.Read())     {         Console.WriteLine("[{0}] {1}, {2} {3}", dr["ID"],             dr["LastName"], dr["FirstName"], dr["MiddleInitial"]);     } } } } 

Note that you have to include the Asynchronous Processing=true option in the connection string in order to enable asynchronous command execution in SQL Server. Also keep in mind that asynchronous processing is not part of the DbCommand abstract base class; it is part of the SqlCommand class only.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: