Executes a database asynchronously but uses code to poll the operation for completion. : Async « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Polling for Completion</title>
</head>
<body>
   
    <div id="pageContent">
        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Execute the command" OnClick="Button1_Click" />
            <hr />
            <asp:Label ID="Results" runat="server"></asp:Label>
        </form>
    </div>
</body>
</html>


File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Default : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        string connString = "Async=true;SERVER=(local);DATABASE=northwind;Trusted_Connection=yes;";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            SqlCommand cmd = new SqlCommand("SELECT lastname,firstname FROM employees", conn);
            conn.Open();
            IAsyncResult iar = cmd.BeginExecuteReader();

            do {
            } while (!iar.IsCompleted);

            SqlDataReader reader = cmd.EndExecuteReader(iar);
            ProcessData(reader);
        }
    }

    protected void ProcessData(SqlDataReader reader)
    {
        StringBuilder sb = new StringBuilder("");
        while (reader.Read())
            sb.AppendFormat("{0}, {1}<br/>", reader[0], reader[1]);

        reader.Close();

        Results.Text = sb.ToString();
    }
}








18.46.Async
18.46.1.Executes a database asynchronously but uses code to poll the operation for completion.
18.46.2.Fire a database asynchronous operation and then proceeds up to the point where results are required