For testing purposes, I am using this directly inside of a razor block in a .cshtml page.
@functions{
public class Inline
{
public HttpResponseBase r { get; set; }
public int Id { get; set; }
public List<System.Threading.Tasks.Task> tasks = new List<System.Threading.Tasks.Task>();
public void Writer(HttpResponseBase response)
{
this.r = response;
tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(
() =>
{
while (true)
{
r.Write("<span>Hello</span>");
System.Threading.Thread.Sleep(1000);
}
}
));
}
}
}
@{
var inL = new Inline();
inL.Writer(Response);
}
I had expected it to write a span with the text “Hello” once every second. It will write “Hello” once sometimes, but not every time or even most times. Why isn’t this task long running?
The reason you are seeing different result is because the task is running asynchronously and if the response object is completed before your task gets a chance to write on it, the taks will throw exception and it will terminate the only way you can do this is if you add Task.WaitAll() at the end of the Writer() method.
This will work but the page will not stop loading content.