CourtesyFlush : A Nuget package for flushing buffers early in ASP.NET MVC

In my previous post I have written about a Nuget package called Polly for Exception handling which you can find here.

In this post I will again write for a Nuget package which is called CourtesyFlush which was before known as PerfMatters.Flush and it is created by Nik

CourtesyFlush , as the name suggests it does the same effect in Coding word which simply means it is forcing a buffer to be moved along, usually to a file or the network. Rather than holding data, you flush it, and move it along.

banner

To install Courtesy Flush, run the following command in the Package Manager Console

image

I will try to explain the effects of this Nuget package by sample Project.

By keeping in mind that you know how to add new project in Asp.Net MVC we are now having below code in our Home controller page.

The only thing we will add in “About” action method is Thread.Sleep(2000).

Reason?

If you have a long running, but important process (we are pretending that Thread.Sleep(2000) is important) that takes 2 seconds, no HTML is sent to the browser. It’s just waiting.

Now basic code would like as below :-


        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }
        public ActionResult About()
        {
            ViewBag.Title = "Your About page.";
            Thread.Sleep(2000);

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

In above scenario there is no HTML is sent to the browser because we are waiting for 2 seconds. The timeline looks like this  

Here we didn't flush

As we can see in above image there is not any javascript or css files loaded until the process completed.

Now CourtseyFlush comes to rescue your application and let javascipt and css file not to wait in a vein like it did in above image.

First of all you need to add _Head.cshtml in shared folder as shown in below image :-

Create new MVC Partial View Menu in Visual studio
And in that view write below piece of code :-

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     @if (ViewBag.Description != null)
     {
         <meta name="description" content="@ViewBag.Description">
     }
     <title>@ViewBag.Title - My ASP.NET Application</title>
     @Styles.Render("~/Content/css")
     @Scripts.Render("~/bundles/modernizr")
</head>

and add @Html.FlushHead() in Layout.cshtml  page as shown below :-

@Html.FlushHead()
 <body>
 <!-- Lots of lovely HTML -->
 <div class="container body-content">
 @RenderBody()
 <hr />
 <footer>
 <p>&copy; @DateTime.Now.Year - My Application</p>
 </footer>
 </div>
 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/bootstrap")
 @RenderSection("scripts", required: false)
 </body>
 </html>

How to use on partilcar action level? 

Three Usage Patterns

The core of what you need to know to use PerfMatters.Flush is that I’ve tried to make it easy to use by providing a few different usage models. Pick the one that works best in your scenario, and feel free to mix and match across your application.

1. Attribute Based

The easiest way to use PerfMatters.Flush is via the [FlushHead] action filter attribute, like this:

[FlushHead(Title = &amp;quot;About&amp;quot;)]
public ActionResult About()
{
      // Do expensive work here
      return View();
}

The attribute can be used alone for HTML documents with a static <head> section. Optionally, a Title property can be set for specifying a dynamic <title> element, which is very common.

2. Code Based

For more complex scenarios, extension methods are provided which allow you to set ViewData or pass along a view model:

public ActionResult About()
{
     ViewBag.Title = &amp;quot;Your About page.&amp;quot;; 
     this.FlushHead();

     return View();
}

As you can see, this mechanism allows for very dynamic <head> sections. In this example you could imagine a <title> element, <meta name="description" content="…"> attribute (for SEO purposes) and <link rel="dns-prefetch" href="…"> (for performance optimization) all being set.

3. Global Lambda

Finally, PerfMatters.Flush offers a model to flush early across all your application’s action methods – which simply leverages the same global action filters that have been in ASP.NET MVC for years now:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     filters.Add(new HandleErrorAttribute());
     filters.Add(new FlushHeadAttribute(actionDescriptor =&amp;gt;
         new ViewDataDictionary&amp;lt;CustomObject&amp;gt;(new CustomObject())
         {
             {&amp;quot;Title&amp;quot;, &amp;quot;Global&amp;quot;},
             {&amp;quot;Description&amp;quot;, &amp;quot;This is the meta description.&amp;quot;}
         }));
}
Let us just take Code Based approach so our particular method would like as below :-
public ActionResult About()
{
    ViewBag.Title = DateTime.Now.Second;
    this.FlushHead();
 
    Thread.Sleep(2000);
    ViewBag.Message = &amp;quot;Your application description page.&amp;quot;;
 
    return View();
}

Here’s what the SAME page looks like with the <head> flushed out first.

Here we flushed
From the above picture it is clear that the formula works and now javascript and css files does not wait till the process completes
Now just look at below image which shows before\after effects :-
difference
After going through this code some might be wondering that Is this package is in use in any live website?
The answer is Yes. It is being used in http://getglimpse.com/ already!

 

Why Flush Early?

Flushing early can provide performance improvements in web applications and has been a recomended best practice in the web performance community since 2007.

To find out more, check out my blog where I covered the benefits of flushing early in two posts:

Happy Coding!


Advertisement

3 thoughts on “CourtesyFlush : A Nuget package for flushing buffers early in ASP.NET MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s