What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 56511 |  Welcome, Guest!   Register  Login
Home > Articles > ADO.NET > Using Asynchronous ADO.Net Method with ASP.Net Asynchronous Page

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

1 vote(s)
Rating: 5 out of 5
Article posted by Vikash on 9/9/2012 | Views: 1862 | Category: ADO.NET | Level: Advance | Points: 250 red flag


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

Introduction


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.

Objective


 This article will give you basic understanding of accessing database asynchronously by using ado.net asynchronous method & asynchronous nature of asp.net 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 ado.net 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);
con.Open();
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"];
results.Add(newMovie);
}
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 ado.net method, you must enable asynchronous asp.net 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 asp.net 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

private AsyncDataLayer dataLayer = new AsyncDataLayer();

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

// Fire off asynchronous tasks
Page.ExecuteRegisteredAsyncTasks();
}

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);
grdMovies.DataBind();
}

void TimeoutData(IAsyncResult ar)
{
// Display error message
lblError.Text = "Could not retrieve data!";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Page AsyncTask</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label
id="lblError"
Runat="server" />

<asp:GridView
id="grdMovies"
Runat="server" />

</div>
</form>
</body>
</html>

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.

Conclusion

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

Best Regards
Vikash Pathak

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:1 year(s)
Home page:http://www.dotnetfunda.com/profile/vikash.aspx
Member since:Monday, June 18, 2012
Level:Starter
Status: [Member]
Biography:1+ yrs exp in .Net & MCP(70-526) paper completed.
>> Write Response - Respond to this post and get points
Related Posts

In this article we will see how we can use the database directly from our application.For this we will be using App_Data folder. We will be detaching and attaching the database for this purpose. Detach is to remove the database instance from Sql Management Studio. Attaching it in .NET app to use the database directly from App.

We will see overview of Changing database records.

In this article, we shall learn how to retrieve data from the database.

We will see overview of ADO.NET Classes . This is the second part of the ADO.NET Series article.

We will see overview of ADO.NET. This is the first part of the ADO.NET Series article.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/24/2013 10:03:22 AM