Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update progress messages while processing data in ASP.NET?

I have a process, that outputs step by step messages (i.e., Processing item 1... Error in item 2 etc etc).

I want this to be output to the user during the process, and not at the end.

I'm pretty sure I need to do this with threading, but can't find a decent example.

like image 933
Danny Avatar asked Mar 27 '10 20:03

Danny


1 Answers

It's not a threading issue, but a web browser UI issue. You want the browser to render the status as you are doing work on the server. In theory you could do something like:

Response.Write("something");
Response.Flush();

but the Flush() won't ensure the browser actually renders your code at that moment. In reality you cannot control how data is cached/chunked/buffered underway from the server to the browser. So each update should be a 'full' http transaction.

One way, and common one, is to use AJAX to achieve this. The user clicks a button which starts some background work, and you have a javascript timer which polls (makes requests) to check the status of the work, and updates the client browser.

Check out Real-Time Progress Bar With ASP.NET AJAX for doing an ajax progress indicator with ajax and .net.

There's an excellent example of creating a progress bar with a http handler in this article: http://www.asp101.com/articles/matt/progressbar/default.asp

To prove my point, the following code works in Firefox, but not in IE or Chrome:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Buffer = false;
    Response.Clear();
    Response.Write("<html><body>");
    Response.Write("1\n");
    Response.Flush();
    Thread.Sleep(2000);
    Response.Write("1\n");
    Response.Flush();
    Thread.Sleep(2000);
    Response.Write("1\n");
    Response.Flush();
    Thread.Sleep(2000);
    Response.Write("1\n");
    Response.Flush();
    Response.Write("</body></html>");
    Response.End();
}
like image 168
Mikael Svenson Avatar answered Nov 14 '22 22:11

Mikael Svenson