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:

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