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("Rozpoczęto asynchroniczne wykonywanie polecenia...");
         Console.ReadLine();
      }

      public static void ExecuteAsync(IAsyncResult ar)
      {
         Thread.Sleep(3000); // symulacja dłuższego zapytania
         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"]);
         }
      }
   }
}
