开发者

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

开发者 https://www.devze.com 2022-12-25 01:30 出处:网络
I have a process, that outputs step by step messages (i.e., Processing item 1... Error in item 2 etc etc).

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 threadi开发者_开发百科ng, but can't find a decent example.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消