Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming text output for long-running action?

I have a few utility actions that return text output via return Content("my text","text/plain").

Sometimes these methods take a few minutes to run (i.e. log parsing, database maintenance).

I would like to modify my action method so that instead of returning all of the output at once, the text is instead streamed to the client when it is ready.

Here's a contrived example:

public ActionResult SlowText()
{
    var sb = new System.Text.StringBuilder();
    sb.AppendLine("This happens quickly...");
    sb.AppendLine("Starting a slow 10 second process...");
    System.Threading.Thread.Sleep(10000);
    sb.AppendLine("All done with 10 second process!");
    return Content(sb.ToString(), "text/plain");
}

As written, this action will return three lines of text after 10 seconds. What I want is a way to keep the response stream open, and return the first two lines immediately, and then the third line after 10 seconds.

I remember doing this 10+ years ago in Classic ASP 3.0 using the Response object. Is there an official, MVC-friendly way to accomplish this?

--

Update: using Razor .cshtml in the app; but not using any views (just ContentResult) for these actions.

like image 526
Portman Avatar asked Jan 04 '11 17:01

Portman


1 Answers

Writing directly to the Response object should work, but only in some simple cases. Many MVC features depend on output writer substitution (e.g. partial views, Razor view engine, and others) and if you write directly to the Response your result will be out of order.

However, if you don't use a view and instead write straight in the controller then you should be fine (assuming your action is not being called as a child action).

like image 129
marcind Avatar answered Nov 05 '22 22:11

marcind