Async SqlConnection in ASP.Net 4.5

Introduction

This article explains how to create an async SqlConnection in ASP .Net 4.5 and using the SqlCommand.BeginExecuteNonQuery Method (AsyncCallback, Object).

So, let's proceed with the following procedure:

  • Create an Asynchronous Page ASP .NET web page
  • Create a Connection, Create a Command, Create a Parameter and Grid View binding

Creating an Asynchronous Page

Create a new project using "File" -> "New" -> "Project..." then select web "ASP .Net Web Forms Application". Name it "AsyncProgramming".

SP .Net Web Forms Application

Next, create the code-behind as follows: The first step to building an asynchronous page is setting the Async attribute in the Page directive to true, as shown here:

  1. <%@ Page Language="C#" Async="true" %>
Async attribute

 

In the web.config file create the database. Set on the connection string: Asynchronous operation to work, the attribute Async=True; as shown here:

Now, in the code behind file AsyncSqlConnection.aspx use the following code.

Async attribute1

  1. <%@ Page Language="C#" Title="Asynchronous programming" Async="true" AutoEventWireup="true"  
  2. CodeBehind="AsyncSqlConnection.aspx.cs" Inherits="AsyncProgramming.AsyncSqlConnection" %>  
  3. <!DOCTYPE html>  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.     <h3 style="font-family: Kartika; font-variant: normal; color: #0000FF; font-style: normal;">Async  
  12. SqlConnection</h3>  
  13.     <p style="color: #FF0000">Student Details</p>   
  14.         <asp:GridView ID="StudentGridView" runat="server" BackColor="White" BorderColor="#CCCCCC"  
  15. BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">  
  16.             <FooterStyle BackColor="#CCCC99" ForeColor="Black" />  
  17.             <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />  
  18.             <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />  
  19.             <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />  
  20.             <SortedAscendingCellStyle BackColor="#F7F7F7" />  
  21.             <SortedAscendingHeaderStyle BackColor="#4B4B4B" />  
  22.             <SortedDescendingCellStyle BackColor="#E5E5E5" />  
  23.             <SortedDescendingHeaderStyle BackColor="#242121" />  
  24.         </asp:GridView>  
  25.     </div>  
  26.     </form>  
  27. </body>  
  28. </html> 

Create Connection, SqlCommand.BeginExecuteNonQuery Method and Grid View Bind

Now, in the code behind file “AsyncSqlConnection.aspx.cs“ use the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. //Using namespaces  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. using System.Configuration;  
  11. using System.Threading.Tasks;  
  12.   
  13. namespace AsyncProgramming  
  14. {  
  15.     public partial class AsyncSqlConnection : System.Web.UI.Page  
  16.     {  
  17.         #region SqlConnection Connection  
  18.         SqlConnection conn = new  
  19. SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);  
  20.         #endregion  
  21.         #region show message  
  22.         /// <summary>  
  23.         /// This function is used for show message.  
  24.         /// </summary>  
  25.         /// <param name="msg"></param>  
  26.         void ShowMessage(string msg)  
  27.         {  
  28.             ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script  
  29. language='javascript'>alert('" + msg + "');</script>");  
  30.         }  
  31.         #endregion  
  32.         protected void Page_Load(object sender, EventArgs e)  
  33.         {  
  34.             PageAsyncTask pat = new PageAsyncTask(BeginAsync, EndAsync, nullnulltrue);  
  35.             this.RegisterAsyncTask(pat);  
  36.         }  
  37.         //BeginAsync() method opens a connection to SQL Server cmd.BeginExecuteNonQuery  
  38.         private IAsyncResult BeginAsync(object sender, EventArgs e, AsyncCallback cb, object state)  
  39.         {  
  40.             conn.Open();  
  41.             SqlCommand cmd = new SqlCommand("Select * from StudentTable WAITFOR DELAY '00:00:01'",  
  42. conn);            
  43.             SqlDataAdapter adp = new SqlDataAdapter(cmd);  
  44.             DataSet ds = new DataSet();  
  45.             adp.Fill(ds);  
  46.             StudentGridView.DataSource = ds;  
  47.             StudentGridView.DataBind();  
  48.             IAsyncResult ar = cmd.BeginExecuteNonQuery(cb, cmd);  
  49.             return ar;  
  50.         }  
  51.   
  52.         //EndAsync() when the async database call completes. EndAsync() calls EndExecuteNonQuery() to complete the command.  
  53.         private void EndAsync(IAsyncResult ar)  
  54.         {  
  55.             using (SqlCommand cmd = (SqlCommand)ar.AsyncState)  
  56.             {  
  57.                 using (cmd.Connection)  
  58.                 {  
  59.                     int rows = cmd.EndExecuteNonQuery(ar);  
  60.                 }  
  61.             }  
  62.         }   
  63.     }  
  64. } 
Run the Page

Async SqlConnection in Aspnet

Now, run in the browser as shown here.

I hope this article is useful. If you have any other questions then please provide your comments in the following.