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:

<%@ 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

<%@ Page Language="C#" Title="Asynchronous programming" Async="true" AutoEventWireup="true"
CodeBehind="AsyncSqlConnection.aspx.cs" Inherits="AsyncProgramming.AsyncSqlConnection" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   
<title></title>
</head>
<body>
   
<form id="form1" runat="server">
   
<div>
   
<h3 style="font-family: Kartika; font-variant: normal; color: #0000FF; font-style: normal;">Async
SqlConnection
</h3>
   
<p style="color: #FF0000">Student Details</p> 
       
<asp:GridView ID="StudentGridView" runat="server" BackColor="White" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
           
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
           
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
           
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
           
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
           
<SortedAscendingCellStyle BackColor="#F7F7F7" />
           
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
           
<SortedDescendingCellStyle BackColor="#E5E5E5" />
           
<SortedDescendingHeaderStyle BackColor="#242121" />
       
</asp:GridView>
   
</div>
   
</form>
</body>
</html>

Create Connection, SqlCommand.BeginExecuteNonQuery Method and Grid View Bind

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


//Using namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading.Tasks;

namespace AsyncProgramming
{
   
public partial class AsyncSqlConnection : System.Web.UI.Page
    {
        #region SqlConnection Connection
       
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
        #endregion
        #region show message
       
/// <summary>
       
/// This function is used for show message.
       
/// </summary>
       
/// <param name="msg"></param>
       
void ShowMessage(string msg)
        {
            ClientScript.RegisterStartupScript(Page.GetType(),
"validation", "<script
language='javascript'>alert('"
+ msg + "');</script>");
        }
        #endregion
       
protected void Page_Load(object sender, EventArgs e)
        {
           
PageAsyncTask pat = new PageAsyncTask(BeginAsync, EndAsync, null, null, true);
           
this.RegisterAsyncTask(pat);
        }
       
//BeginAsync() method opens a connection to SQL Server cmd.BeginExecuteNonQuery
       
private IAsyncResult BeginAsync(object sender, EventArgs e, AsyncCallback cb, object state)
        {
            conn.Open();
           
SqlCommand cmd = new SqlCommand("Select * from StudentTable WAITFOR DELAY '00:00:01'",
conn);          
           
SqlDataAdapter adp = new SqlDataAdapter(cmd);
           
DataSet ds = new DataSet();
            adp.Fill(ds);
            StudentGridView.DataSource = ds;
            StudentGridView.DataBind();
           
IAsyncResult ar = cmd.BeginExecuteNonQuery(cb, cmd);
           
return ar;
        }

       
//EndAsync() when the async database call completes. EndAsync() calls EndExecuteNonQuery() to complete the command.
       
private void EndAsync(IAsyncResult ar)
        {
           
using (SqlCommand cmd = (SqlCommand)ar.AsyncState)
            {
               
using (cmd.Connection)
                {
                   
int rows = cmd.EndExecuteNonQuery(ar);
                }
            }
        } 
    }
}


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.

Up Next
    Ebook Download
    View all
    Learn
    View all