Introduction
I would like to share the usage of Response.BufferOutput to improve the performance of ASP.Net application.
Objective
We will learn about the "BufferOutput" property of the HttpResponse Class. It is basically a Boolean property.
Description
By default Respose.BufferOutput is enabled in ASP.Net, in ohter words Response.BufferOutput =true, which means that all the output from your ASP is actually sent to the browser only when the page completes its processing
This approach has the following problems.
The client might need to wait until all the processing has completed on the server, because the server will send the response back to the client only when the page completes its processing.
- If the server is taking a lot of time to process the request then the client must wait a long time and that is not a good approach.
- Servers need to retain a huge amount of data in memory.
Solution
We can avoid such situations by using Response.BufferOutput =false.
Example
I created a sample application and wrote a sample code as per the following.
Page_Load()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
Response.Write(i + "\n");
}
}
Code Explanation
In the code above I am simply trying to display 1 to 99 on the client screen / browser.
Here the client will get the output after 100 seconds because we have used Thread.sleep(1000) = 1 sec.
So in the code above the client must wait; that is not good.
Solution
We have used Response.BufferOutPut=false at the server as in the code below.
Page_Load()
{
Response.BufferOutput = false;
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
Response.Write(i + "\n");
}
}
Here from the code above, the client does not need to wait 100 seconds, the client will get the output on each and every second.
The data will be transferred to the client in chunks. We would see the updated screen after each and every second.
When I debug the Httprequest and Httpresponse, I saw that data has been transferred in chunks.
The following is a snapshot of the solution approach above. Here we can see Transfer-encoding : Chunked.
For More on HTTP debugging kindly see the following link:
Debugging HTTP Requests and HTTP Responses
Conclusion
We can improve the performance of an ASP.Net application using this technique.
References
Chapter 6 - Improving ASP.NET Performance