Perform Asynchronous Database Operations Against SQL Server - CSharp Database

CSharp examples for Database:SQL Command

Description

Perform Asynchronous Database Operations Against SQL Server

Demo Code


using System;/*w  w w  .ja  va2s  .  co m*/
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())
                        {
                            // Display the product details.
                            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);
                }
            }

        }
    }

Result


Related Tutorials