Caching



Caching

Another design tip to keep in mind is to use .NET's caching features. There are two related features in ASP.NET Web Services that enable the developer to cache responses and application data.

The first is called output caching, and it is available right on the [WebMethod] attribute. The CacheDuration property, when set, will remember the response to send for the time limit specified. This means that your logic will not be called. If you know that the logic doesn't need to be called, then this is a good option. Here is an example:

[WebMethod( CacheDuration=60 )] 
public StockData GetStockData()
{
     //insert database query here
}

As you can probably tell, this works best for Web service operations that focus on returning data. An operation that wasn't a get but more a set or update operation wouldn't be a good candidate for output caching.

You can also take advantage of ASP.NET's application caching with the Cache object. This class lets you stuff custom objects into its cache, and then specify specific timeouts or even files or folders to watch for changes to invalidate the cache.

Here is an example of inserting some data:

Cache.Insert("CachedStockData", StockQuoteData, null, 
                    DateTime.Now.AddMinutes(15), TimeSpan.Zero);

You can then look for this value, and if it is not null, use the value found in the cache:

StockQuoteData = Cache["CacheStockData"]; 
if(StockQuoteData != null )
{
      //do something with the data
}