Introduction:
In this article, i am going to explain about how to create/perform asynchronous database operations against sql server using asp.net/c#.
Main:
The below methods in system.data.sqlclient class supports the asynchronous background task,the methods are
BeginExecuteNonQuery,
BeginExecuteReader,
BeginExecuteXmlReader
These methods all return a System.IAsyncResult object that you can use to determine the operation’s status or use thread synchronization to wait for completion. Use the IAsyncResult object and the corresponding EndExecuteNonQuery, EndExecuteReader, or EndExecuteXmlReader method to obtain the result of the operation.
See this below examble,
using System;
using System.Data;
using System.Threading;
using System.Data.SqlClient;
namespace AsyncDatabaseOps
{
class Async
{
// A method to handle asynchronous completion using callbacks.
public static void CallbackHandler(IAsyncResult result)
{
// Obtain a reference to the SqlCommand used to initiate the
// asynchronous operation.
using (SqlCommand cmd = result.AsyncState as SqlCommand)
{
// Obtain the result of the stored procedure.
using (SqlDataReader reader = cmd.EndExecuteReader(result))
{
// Display the results of the stored procedure to the console.
lock (Console.Out)
{
Console.WriteLine(
"This is async database operation:");
while (reader.Read())
{
// Display the product details.
Console.WriteLine(" {0} = {1}",
reader["EmpName"],
reader["EmpId"]);
}
}
}
}
}
public static void Main()
{
// Create a new SqlConnection object.
using (SqlConnection con = new SqlConnection())
{
// Configure the SqlConnection object's connection string.
// You must specify Asynchronous Processing=true to support
// asynchronous operations over the connection.
con.ConnectionString = @"Data Source = .sqlexpress;" +
"Database = Northwind; Integrated Security=SSPI;" +
"Asynchronous Processing=true";
// Create and configure a new command to run a stored procedure.
// Do not wrap it in a using statement because the asynchronous
// completion handler will dispose of the SqlCommand object.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Ten Most Expensive Products";
// Open the database connection and execute the command
// asynchronously. Pass the reference to the SqlCommand
// used to initiate the asynchronous operation.
con.Open();
cmd.BeginExecuteReader(CallbackHandler, cmd);
// Continue with other processing.
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);
}
}
// Wait to continue.
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Main method complete. Press Enter.");
Console.ReadLine();
}
}
}
using System; using System.Data; using System.Threading; using System.Data.SqlClient; namespace AsyncDatabaseOps { class Async { // A method to handle asynchronous completion using callbacks. public static void CallbackHandler(IAsyncResult result) { // Obtain a reference to the SqlCommand used to initiate the // asynchronous operation. using (SqlCommand cmd = result.AsyncState as SqlCommand) { // Obtain the result of the stored procedure. using (SqlDataReader reader = cmd.EndExecuteReader(result)) { // Display the results of the stored procedure to the console. lock (Console.Out) { Console.WriteLine( "This is async database operation:"); while (reader.Read()) { // Display the product details. Console.WriteLine(" {0} = {1}", reader["EmpName"], reader["EmpId"]); } } } } } public static void Main() { // Create a new SqlConnection object. using (SqlConnection con = new SqlConnection()) { // Configure the SqlConnection object's connection string. // You must specify Asynchronous Processing=true to support // asynchronous operations over the connection. con.ConnectionString = @"Data Source = .sqlexpress;" + "Database = Northwind; Integrated Security=SSPI;" + "Asynchronous Processing=true"; // Create and configure a new command to run a stored procedure. // Do not wrap it in a using statement because the asynchronous // completion handler will dispose of the SqlCommand object. SqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Ten Most Expensive Products"; // Open the database connection and execute the command // asynchronously. Pass the reference to the SqlCommand // used to initiate the asynchronous operation. con.Open(); cmd.BeginExecuteReader(CallbackHandler, cmd); // Continue with other processing. 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); } } // Wait to continue. Console.WriteLine(Environment.NewLine); Console.WriteLine("Main method complete. Press Enter."); Console.ReadLine(); } } } |
Conclusion:
Hope this helps,
Happy coding.
Great information! I’ve been looking for something like this for a while now. Thanks!
Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.