We all have user controls that appear on every page (a perfect example of this - a header control or a navigation control). User controls can very easily be cached using the
<%@ OutputCache duration="3600"%>
By embedding the above tag into a user control, it will be cached for an hour. But what if the data it displays changes during the course of the hour? How do I ensure that the data will be updated in a timely manner? The simple solution is in the
VaryByCustomattribute of the tag.
VaryByCustomcalls a special function called
GetVaryByCustomStringand passes it the value you specify for the
VaryByCustomattribute in the
OutputCachetag. Essentially you write the code to determine what value gets returned. With each subsequent request for the cached object, the ASP.Net engine first checks the result
GetVaryByCustomStringfunction. If the result has changed - regardless of the duration on the Cache, the system will bypass the cache and execute the code in the control.
Therefore, it is very easy to set up, say, an application variable that gets changed only when the data gets changed, then use the
GetVaryByCustomStringfunction to check for updates.
OutputCacheline will now look like this:
<%@ OutputCache duration="3600" VaryByCustom="updateCheck"%>
Then make the following changes to your
- Add the following line to your
- Add the following code as the function
public override string GetVaryByCustomString(HttpContext context,string arg)
//We need to return an empty string so that this compiles
Now you are almost done. All you still need to do to ensure that your cached pages are updated when data changes is to make the following call:
This will update the application variable, and change the result of the
GetVaryByCustomStringfunction, which will force the Cache to update.