Click here to Skip to main content
Click here to Skip to main content

Use the Asynchronous Power of ASP.NET to Create a Simple, Reusable Page for Displaying a Processing Message

By , 11 Jul 2005
 

Sample Image - ProcessingMessage.gif

Introduction

Sometimes we may find it necessary for our users to run long processes when using the web as a user interface. Since patience is not a typical trait of web users, we run into the issue of needing to entertain them, prevent multiple clicks, or keep them from pulling their hair out while we're running time-consuming processes in the background. There are several tactics for doing this on the web, but I have found none of these to be as simple as employing .NET's asynchronous threading. I hope that you find this helpful.

Using the code

The relevant portion of the sample application included with this article consists of two C# Web Forms i.e., SubmitLongProcess.aspx, ProcessingMessage.aspx. SubmitLongProcess.aspx is used for starting the process and redirecting the user to ProcessingMessage.aspx. ProcessingMessage.aspx is the processing message page that is used to display a friendly message to the user while the long process is running in the background. Once the long process completes, ProcessingMessage.aspx redirects the user to a specified page.

SubmitLongProcess.aspx

As you can see in the code below, .NET makes firing off a new thread quite simple. Without fully qualifying the code, you'll need to include a using directive to the System.Web.Threading namespace.

using System.Web.Threading

You can see that all I'm doing in the SubmitButton_Click event is initializing the session variable, initializing and starting the new thread, then redirecting the user to the ProcessingMessage.aspx page. Notice that I've included two querystring name/value pairs in the URL parameter of the Response.Redirect method. One is used to specify the redirect page after processing is complete and the other is used to inform ProcessingMessage.aspx what session variable to check.

Response.Redirect("ProcessingMessage.aspx?redirectPage" + 
      "=SubmitLongProcess.aspx&ProcessSessionName=" + PROCESS_NAME);

The StartLongProcess() method runs in the background on a new thread while the user is redirected to the ProcessingMessage.aspx page. This method consists of two important lines of code. The first is used to mimic a long process by forcing the thread to sleep for a specified amount of time. Once the thread is done sleeping, the second line of code is used to set the session variable equal to true. Setting this variable equal to true informs the ProcessingMessage.aspx that the long process is complete.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Threading;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace AsynchronousProcessing
{
    public class ProcessingMessage : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.TextBox txtProcessLength;
        protected System.Web.UI.WebControls.Button SubmitButton;
        private const string PROCESS_NAME = "Process";

        private void Page_Load(object sender, System.EventArgs e)
        {

        }

        private void SubmitButton_Click(object sender, System.EventArgs e)
        {
            //Initialize Session Variable
            Session[PROCESS_NAME] = false;

            //Create and initialize new thread with the 
            //address of the StartLongProcess function
            Thread thread = new Thread(new ThreadStart(StartLongProcess));

            //Start thread
            thread.Start();

            //Pass redirect page and session var name 
            //to the process wait (interum) page
            Response.Redirect("ProcessingMessage.aspx?" + 
              "redirectPage=SubmitLongProcess.aspx&ProcessSessionName=" 
              + PROCESS_NAME);
        }

        private void StartLongProcess()
        {
            //Replace the following line of code with your long process
            Thread.Sleep(Convert.ToInt32(this.txtProcessLength.Text)* 1000);

            //Set session variable equal to true when process completes
            Session[PROCESS_NAME] = true;
        }
    }
}

ProcessingMessage.aspx

The ProcessingMessage.aspx page is used to inform the user how long he/she has waited and redirects the user to the specified page when the long process is complete. With the source code, I've included a simple yet effective animated gif called Processing.gif that's used to simulate a process occurring in the background. I've also forced the page to refresh every second by adding the equiv-refresh meta tag to the aspx portion of the Web form.

<meta http-equiv="refresh" content="1">

In the Page_Load method, I am setting a session variable called Session["ProcessTime"]. This variable is used to keep track of how long the process has been running and display this to the user. Every time the page refreshes, Session["ProcessTime"] is incremented by 1.

Session["ProcessTime"] = Convert.ToInt32(Session["ProcessTime"]) + 1;

You'll also notice that I'm checking the state of the session variable that's waiting to be set on the triggering page. Once this variable equals true, I set both the Session[processSessionName] and Session["ProcessTime"] equal to null and redirect the user to the page specified in the querystring. I set the session variables equal to null in case the user performs another long process within the same session.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace AsynchronousProcessing
{
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Label StatusMessage;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            string redirectPage = Request.QueryString["redirectPage"];
            string processSessionName = Request.QueryString["ProcessSessionName"];
            if (Session["ProcessTime"] == null)
            {
                StatusMessage.Text = "Process has been running for 0 seconds";
                Session["ProcessTime"] = 0;
            }
            else
            {
                Session["ProcessTime"] = Convert.ToInt32(Session["ProcessTime"]) + 1;
                StatusMessage.Text = "Process has been running for " + 
                        Session["ProcessTime"].ToString() + " seconds";
            }

            if ((bool)Session[processSessionName] == true)
            {
                Session[processSessionName] = null;
                Session["ProcessTime"] = null;
                Response.Redirect(redirectPage);
            }
        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Brandon Noffsinger
Web Developer
United States United States
Member
I don't really have much to say at this point. I promise to update this if I come up with another article to submit.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralWell done - great sample [modified]memberTaner Riffat24 Apr '10 - 2:00 
GeneralDoesn't work in 3.0membercsandvig16 Jun '08 - 7:44 
GeneralRe: Doesn't work in 3.0 [modified]memberTaner Riffat24 Apr '10 - 1:58 
Generalhuge problemmemberGevorg30 Oct '07 - 5:03 
GeneralRe: huge problem [modified]memberTaner Riffat24 Apr '10 - 2:02 
GeneralVery NicememberZeeshan Reyaz3 Oct '07 - 2:14 
QuestionHow do I get information back from the...membertravich5 Jan '07 - 19:26 
AnswerRe: How do I get information back from the...memberph0o4 Sep '07 - 3:16 
GeneralMy thread doesn't even appear launtchedmemberAndre Dias1 Jan '07 - 23:06 
QuestionWhat if I don't want a wait page? [modified]memberEnoughToBeDangerous23 Aug '06 - 4:27 
GeneralLosing Session ProblemmemberMickAllen24 Mar '06 - 10:16 
GeneralHaving a problem with view statemembersombra2137 Mar '06 - 10:44 
GeneralRe: Having a problem with view statemembernamenotchosen12 Apr '06 - 5:37 
GeneralRe: Having a problem with view statememberOzSoft Solutions25 Apr '06 - 15:47 
GeneralRe: Having a problem with view statememberoleano29 Mar '07 - 11:32 
GeneralProblemmemberBeetle5429 Aug '05 - 10:55 
GeneralRe: ProblemmemberBrandon Noffsinger29 Aug '05 - 11:05 
GeneralLittle problem in vbmemberLumenm16 Aug '05 - 4:05 
GeneralRe: Little problem in vbmemberBrandon Noffsinger16 Aug '05 - 4:56 
GeneralRe: Little problem in vbmemberLumenm16 Aug '05 - 5:32 
GeneralRe: Little problem in vbmemberLumenm18 Aug '05 - 1:38 
Generalthreading errormemberLumenm18 Aug '05 - 23:06 
GeneralRe: threading errormemberBrandon Noffsinger19 Aug '05 - 5:40 
GeneralRe: threading errormemberLumenm19 Aug '05 - 10:02 
AnswerRe: threading errormemberLumenm15 Sep '05 - 5:50 
GeneralRe: threading errormemberBrandon Noffsinger15 Sep '05 - 5:58 
GeneralRe: threading errormemberLumenm15 Sep '05 - 22:01 
GeneralRe: threading errormemberLumenm16 Sep '05 - 1:54 
AnswerRe: threading errormemberLumenm16 Sep '05 - 5:46 
GeneralRe: threading errormemberBrandon Noffsinger16 Sep '05 - 5:58 
GeneralPERFECTmemberdclark10 Aug '05 - 16:09 
GeneralDoen not work with SessionState modemembervickycao31 Jul '05 - 15:11 
GeneralRe: Doen not work with SessionState modememberBrandon Noffsinger1 Aug '05 - 8:08 
GeneralRe: Doen not work with SessionState modemembervickycao1 Aug '05 - 15:26 
GeneralRe: Doen not work with SessionState modememberBrandon Noffsinger2 Aug '05 - 9:32 
GeneralRe: Doen not work with SessionState modemembervickycao2 Aug '05 - 15:20 
GeneralRe: Doen not work with SessionState modememberBrandon Noffsinger3 Aug '05 - 8:20 
GeneralRe: Doen not work with SessionState modemembervickycao3 Aug '05 - 23:29 
GeneralRe: Doen not work with SessionState modememberBrandon Noffsinger4 Aug '05 - 5:24 
GeneralDarn itmemberBlairs12 Jul '05 - 5:54 
GeneralRe: Darn itmemberBrandon Noffsinger13 Jul '05 - 8:28 
GeneralRe: Darn itmemberBlairs13 Jul '05 - 8:33 
GeneralThanks !memberTrance Junkie12 Jul '05 - 2:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 11 Jul 2005
Article Copyright 2005 by Brandon Noffsinger
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid