26

I have code like this:

context.HttpContext.Response.Clear();
context.HttpContext.Response.Write(htmlString);              
context.HttpContext.Response.End(); 

But when pages are loaded I have an unclosed HTML tag in them. When I replace Response.End() with Response.Flush() it works fine.

What is difference between Response.End() and Response.Flush()?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Cipiripi
  • 1,123
  • 5
  • 17
  • 33

1 Answers1

32

Response.Flush

Forces all currently buffered output to be sent to the client. The Flush method can be called multiple times during request processing.

Response.End

Sends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.

You should try using this code if you are not doing any processing on the page after Response.Write and want to stop processing the page.

    context.HttpContext.Response.Clear();
    context.HttpContext.Response.Write(htmlString);              
    context.HttpContext.Response.Flush(); // send all buffered output to client 
    context.HttpContext.Response.End(); // response.end would work fine now.
ericosg
  • 4,926
  • 4
  • 37
  • 59
DotNetUser
  • 6,494
  • 1
  • 25
  • 27
  • 3
    I'm curious if it's really necessary to call `Flush()` before `End()` here? From the definitions you provide, `End` does the same thing as `Flush` before stopping the page execution and raising `EndRequest`...so why is it prudent to call `Flush()` before `End()`? – Robert Petz Apr 08 '14 at 20:50
  • 5
    nevermind, I have a complex setup in my code that involves the above code and when I remove the `Flush()` I get exceptions stating that the thread is being aborted. – Robert Petz Apr 08 '14 at 20:57
  • 3
    From the documentation as shown it would appear as if you don't need to call Flush before End, but in practice all kinds of errors happen when calling End without Flush. – Roland Aug 09 '16 at 09:07
  • 1
    Interesting, "but in practice all kinds of errors happen when calling End without Flush", I'm experiencing an issue "System.Web.HttpException: Server cannot set status after HTTP headers have been sent." when I call Flush immediately followed by End so am trialling commenting out the Flush line. – mattpm Aug 15 '18 at 03:16