【IT168技术文档】
使用SqlCommand类的BeginExecuteNonQuery、BeginExecuteReader或 BeginExecuteXmlReader方法开始执行一个后台数据库操作。这些方法都会返回一个System.IAsyncResult对象,我们可以用它来获取操作的状态或使用同步线程等待该操作完成。使用IAsyncResult对象及SqlCommand相应的 EndExecuteNonQuery、EndExecuteReader或EndExecuteXmlReader方法来获取操作的结果。
class Program { public static void CallbackHandler(IAsyncResult result) { using (SqlCommand cmd = result.AsyncState as SqlCommand) { using (SqlDataReader reader = cmd.EndExecuteReader(result)) { lock (Console.Out) { Console.WriteLine("Price of the The Most Expensive Products:"); while (reader.Read()) { Console.WriteLine(" {0} = {1}", reader["TenMostExpensiveProducts"], reader["UnitPrice"]); } } } } } static void Main(string[] args) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = @"server=(local);database=Northwind;uid=sa;Asynchronous Processing=true"; SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Ten Most Expensive Products"; conn.Open(); cmd.BeginExecuteReader(CallbackHandler, cmd); for (int count = 0; count < 10; count++) { lock (Console.Out) { Console.WriteLine("{0} : Continue processing", DateTime.Now.ToString("HH:mm:ss.ffff")); } Thread.Sleep(400); } } Console.WriteLine(); Console.ReadLine(); } }