Monday 20 December 2010

ASP: The Response.Flush method

   


Experience in programming is something that comes with time. You always learn something new, especially when you need to solve an issue. Sometimes, having a problem, a syntax error thrown by your favourite browser, could be the right moment to learn a new trick. Solved the problem, you might soon forget about the solution, or you might forget to understand better the solution. That is what happened to me with Response.Flush and in this post I would like to get a deeper look at it.

The Flush method
The Flush method, when called, sends the output to the client browser immediately. You might wonder when should you use it. It is advisable to use the method whenever you need to output your page immediately. If you think about a great amount of data fetched by a query, you might want to start showing to the client something immediately, just to make him aware of the fact that the data is being retrieved. Specifically, the Flush method sends buffered HTML output immediately. By default, on IIS buffering is enabled. It means that the asp page is actually sent to the client's browser only when the page itself is completely processed. As a result, the client might believe that everything is slowing down or freezing. And, believe me, you do not want that to happen. Again the Flush method - in those cases - is the answer.

How to use it
First of all, you need to set the buffer to true, otherwise your browser might throw an error. In ASP version 2.0, the buffer is by default set to False, while from ASP version 3.0 and later the buffer is set already to True by default.
Just to avoid problems, set it to True at the beginning of you page:
<%Response.Buffer = True%>
Build your page as usual, however, when doing it, start locating suitable spots for your flushes. Basically you can put some text and then use the flush method, like:
Just some text as an example...
<%Response.Flush%>
You can call the Flush method wherever you need to and more than once. However it is advisable not to call it too many times. For example, if your page is retrieving 10.000 records, you do not want to use the method for every record.

Some things you should remember
First of all, you must remember that your server will not follow KeepAlive requests for your page after calling the Flush method.
If you use a Response.Redirect in your page, you must use the Flush method after the redirect.
If your page is working with cookies, you have to deal with them before the Flush method.

Please, remember to share your thoughts in the comment section below.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.