/re'kersiv/$ cd aaron/Entry$ cat FasterPageLoadTimesWithOutputCacheAndTaskScheduler.txt

Faster Page Load Times With OutputCache And Task Scheduler

Tue 04/28/2020

This site runs on a mini pc (read about that here) with a sqlite database, so the odds are not in my favor when it comes to fast page loads.  While I am probably the only one reading my site at this point, I despise waiting for web pages to load.  So in order to keep my reader happy, I have employed a couple strategies that have helped improve site performance quite a bit.


Output Caching via ASP.NET MVC’s OutputCache Attribute

The OutputCache attribute is a very simple way to layer in server-side caching of ASP.NET MVC routes.  There are a ton of options with this approach, but for this application my needs were simple.  First up, I needed to cache rendered views, but not the same rendering for all users.  In this case I used the VaryByCustom parameter and implemented it to ready the requesting user’s Identity info.  For this site, that basically means authenticated vs. unauthenticated users.  Secondly, I needed to store some dynamically generated images that I only wanted cached on the server so that the client would retrieve the latest available version.

There are some options on how to implement this Attribute, but I strongly recommend only using the CacheProfile approach so that your cache setting particulars can be separate from your code.

That means a new section in your web.config, inside <system.web> 

          <add name="UserCache" duration="600" location="ServerAndClient" varyByCustom="User"/>
          <add name="ImageCache" duration="60" location="Server" />


With that config shown above, I then can apply my caching attributes to any actions I want.

[OutputCache(CacheProfile = "UserCache")]
public ActionResult About() 

[OutputCache(CacheProfile = "ImageCache")]
public ActionResult FreeMem()


In order to correctly complete the VaryByCustom logic, I overrode the GetVaryByCustomString method in Global.asax.

public override string GetVaryByCustomString(HttpContext context, string custom)
     return "User".Equals(custom, StringComparison.OrdinalIgnoreCase)
                ? User.Identity.Name
                : base.GetVaryByCustomString(context, custom);


Read the docs for more info on OutputCache here:


Priming via “KeepAlive” Task Scheduler Tasks

With all of that caching weaved in place,  I can keep the site “warmed up” and ready for that dedicated reader.  I used Windows built in Task Scheduler and a couple powershell scripts for this purpose.

One example of such script is keepAlive.ps1


Then in Task Scheduler create a task that runs a program, in this case powershell.exe, with the arguments “-ExecutionPolicy Bypass -File C:\Users\Aaron\scripts\keepAlive.ps1” and run it every 5 minutes.


There you have it, quick page loads even from my anemic little server.