Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

SqlCommand with Callback Handler

using System; using System.Data; using System.Threading; using System.Data.SqlClient; class MainClass {     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 Ten Most Expensive Products:");                     while (reader.Read()) {                         Console.WriteLine("  {0} = {1}",                             reader["TenMostExpensiveProducts"],                             reader["UnitPrice"]);                     }                 }             }         }     }     public static void Main() {         using (SqlConnection con = new SqlConnection()) {             con.ConnectionString = @"Data Source = .\sqlexpress;" +                 "Database = Northwind; Integrated Security=SSPI;" +                 "Asynchronous Processing=true";             SqlCommand cmd = con.CreateCommand();             cmd.CommandType = CommandType.StoredProcedure;             cmd.CommandText = "Ten Most Expensive Products";             con.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(500);             }         }     } }