Reputation: 2168
I am working with an API that runs pretty slowly, and as a result my application is taking a pretty big performance hit. I have managed to optimize some of the code and cut down the loading time considerably, but I would also like to cache some data across all sessions to minimize the amount of server hits I have to make. There is one API call I make now that takes almost 10 seconds to run, and the data returned rarely changes (maybe once every few weeks). What I would like to do is cache that result, as well as the time it was retrieved, and only make the API call if a certain amount of time has passed since the last call, otherwise returning the cached results. Currently I am attempting this:
[WebMethod]
public List<RegionList> getRegionLists() {
if (GlobalAppCache.RegionListsLastUpdate == DateTime.MinValue || GlobalAppCache.RegionListsLastUpdate.AddMinutes(15) > DateTime.Now)
{
List<RegionList> regionLists = new List<RegionList>( );
// Do Some API Calls
GlobalAppCache.RegionListsLastUpdate = DateTime.Now;
GlobalAppCache.CachedRegionLists = regionLists;
return regionLists;
}
return GlobalAppCache.CachedRegionLists;
}
With the GlobalAppCache class being:
public class GlobalAppCache {
public static DateTime RegionListsLastUpdate{get;set;}
public static List<RegionList> CachedRegionLists{get;set;}
}
This method of caching doesn't appear to be working (The API Call is made every time, and the cached results are never returned), and I haven't been able to get anything having to do with the Application[] array to work either. Could anyone point me in the right direction? If I can get this working I may be able to improve performance by caching more items in this GlobalAppCache object. Thanks!
Upvotes: 0
Views: 1799
Reputation: 2168
Ok, I have found a solution for my issue. Apparently while reading the documentation for the WebMethod flag, I missed the CacheDuration property. Since I was trying to cache the output of my methods, simply changing
[WebMethod]
to
[WebMethod(CacheDuration = (60*60*24*2))]
fixed it!
Upvotes: 0
Reputation: 435
Try writing to the HttpApplicationState object Application. When retrieving the Data you should pay attention to the casting to correct datatype:
Application["LastUpdate"] = DateTime.Now;
.. .. ..
object o = Application["LastUpdate"];
if (o != null) DateTime dLastUpdate = Convert.ToDateTime(o);
... ...
The Application object dies when the AppPool the webservice runs in gets restarted / recycled
Upvotes: 1