Using Asynchronous ADO.Net Method with ASP.Net Asynchronous Page

Posted by in ADO.NET category on for Advance level | Points: 250 | Views : 7294 red flag
Rating: 5 out of 5  
 1 vote(s)

Here, I am going to introduce you with asynchronous method which works asynchronously for any operation on database.


ADO.Net 2.0 introduces asynchronous versions of several of its methods.These methds come in pairs: Begin and End method and provides asynchronous DML, DQL, etc, operations on the database.


 This article will give you basic understanding of accessing database asynchronously by using asynchronous method & asynchronous nature of pages.

Using the code

Some methods for SqlCommand objects, for example, are

  1. BeginExecuteNonQuery()
  2. EndExecuteNonQuery()
  3. BeginExecuteReader()
  4. EndExecuteReader()

To use these asynchronous methods, you must use a special attribute in your connection string the
 Asynchronous Processing=true

I am using a table named Movies that have following structure
Title                Director
Movie_name      Director_Name

Below, i have defined a data access component AsyncDataLayer containing BeginGetMovies() and EndGetMovies() method that fetch movie from Movies table asynchronously. These two methods use the BeginExecuteReader() and EndExecuteReader() to fetch a datareader asynchronously.
The AsyncDataLayer component is as follow

public class AsyncDataLayer
private static readonly string _connectionString;
private SqlCommand _cmdMovies;
public IAsyncResult BeginGetMovies(AsyncCallback callback, object state)
SqlConnection con = new SqlConnection(_connectionString);
_cmdMovies = new SqlCommand("WAITFOR DELAY '0:0:0';select title,director from movie", con);
return _cmdMovies.BeginExecuteReader(callback, state, CommandBehavior.CloseConnection);
public List<AsyncDataLayer.Movie> EndGetMovies(IAsyncResult result)
List<AsyncDataLayer.Movie> results = new List<AsyncDataLayer.Movie>();
SqlDataReader reader = _cmdMovies.EndExecuteReader(result);
while (reader.Read())
AsyncDataLayer.Movie newMovie = new AsyncDataLayer.Movie();
newMovie.Title = (string)reader["Title"];
newMovie.Director = (string)reader["Director"];
return results;

static AsyncDataLayer()
_connectionString = WebConfigurationManager.ConnectionStrings["Movies"].ConnectionString +
";Asynchronous Processing=true";

public class Movie
private string _title;

public string Title
get { return _title; }
set { _title = value; }
private string _director;

public string Director
get { return _director; }
set { _director = value; }


For taking advantage of asynchronous method, you must enable asynchronous page execution. Enable page execution by adding following line in page directive.

<%@ Page Async="true" AsyncTimeout="1" Trace="true" %>

The first attribute enables asynchronous page execution and second attribute specifies a timeout value in seconds. After you enable asynchronous page execution , we set up asynchronous task and register this task with the page.

The complete code for page is given below

<%@ Page Language="C#" Async="true" AsyncTimeout="1" Trace="true" %>
<%@ Import Namespace="System.Threading" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<script runat="server">

private AsyncDataLayer dataLayer = new AsyncDataLayer();

void Page_Load()
// Setup asynchronous data execution
PageAsyncTask task = new PageAsyncTask(BeginGetData, EndGetData, TimeoutData, null, true);

// Fire off asynchronous tasks

IAsyncResult BeginGetData(object sender, EventArgs e, AsyncCallback callback, object state)
// Show Page Thread ID
Trace.Warn("BeginGetData: " + Thread.CurrentThread.GetHashCode());

// Execute asynchronous command
return dataLayer.BeginGetMovies(callback, state);

void EndGetData(IAsyncResult ar)
// Show Page Thread ID
Trace.Warn("EndGetDate: " + Thread.CurrentThread.GetHashCode());

// Bind results
grdMovies.DataSource = dataLayer.EndGetMovies(ar);

void TimeoutData(IAsyncResult ar)
// Display error message
lblError.Text = "Could not retrieve data!";
<html xmlns="" >
<head id="Head1" runat="server">
<title>Show Page AsyncTask</title>
<form id="form1" runat="server">

Runat="server" />

Runat="server" />


The constructor for the PageAsyncTask object accepts the following parameters:

beginHandler - method that executes when asynchronous task begins

endHandler-method that executes when asynchronous task ends.

timeoutHandler - this method executes when the asynchronous task go out of time according to the Page directive's AsyncTimeout attribute.

state - an arbitrary object that represents state information.

executeInParallel - A boolean value that indicates whether multiple asynchronous tasks should execute at the same time or execute in sequence.

the OutPut of the complete operation is shown below

For checking this operation change the AsyncTimeout  in page directive and 'WAITFOR DELAY 0:0:1' in the AsyncDataLayer component.


It will give a basic understanding of asynchronous nature of method and page.

Best Regards
Vikash Pathak

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: vikash pathak
Member Level: Starter
Member Status: Member
Member Since: 6/18/2012 7:46:35 AM
Country: India
Regards, Vikash Pathak
1+ yrs exp in .Net & MCP(70-526) paper completed.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)