'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.



Solution 1:[1]

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();
}

Solution 2:[2]

use two way communication methods, such as webRTC or signalR or gRPC, send live messages from server to client web browser.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Grace Streaming