I've researched, tapped friends and still can't get this to work. Even Caching in a console application really doesn't answer the question.
I have a scheduled task that runs this app once an hour for the next 12 hours that uses last years data as reference.
Of course, last years data is not going to change, a perfect case to use cache, especially since the query takes 90 to 110 seconds to run depending on how busy the server is.
using System.Runtime.Caching;
private static ObjectCache o_Cache = MemoryCache.Default;
private static IEnumerable<SWFSalesModel> GetLastYearsSalesData(ObjectCache o_Cache, string cacheKey) {
IEnumerable<SWFSalesModel> arrLastYearsData = o_Cache.GetCacheItem(cacheKey) as IEnumerable<SWFSalesModel>;
if (arrLastYearsData == null) {
Console.WriteLine("Look in the cache 2");
arrLastYearsData = (IEnumerable<SWFSalesModel>)o_Cache.Get(cacheKey);
}
if (arrLastYearsData == null) {
Console.WriteLine("Look in the cache 3");
arrLastYearsData = (IEnumerable<SWFSalesModel>)o_Cache[cacheKey];
}
if (arrLastYearsData != null) {
return arrLastYearsData;
} else {
Console.WriteLine("nope, not in the cache");
arrLastYearsData = GetLastYearSales(); ;
CacheItemPolicy policy = new CacheItemPolicy();
Console.WriteLine("Adding to the cache...");
policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(12.0);
o_Cache.Add(cacheKey, arrLastYearsData, policy);
IEnumerable<SWFSalesModel> arrTest = (IEnumerable<SWFSalesModel>)o_Cache[cacheKey];
if (arrTest != null) {
/* This works 100% of the time */
Console.WriteLine("it's in test cache!");
} else {
Console.WriteLine("nope, nada in test cache");
}
return arrLastYearsData;
}
}
Then called in the program:
/* Get Last Years Sales Data */
string cacheKey = DateTime.Today.ToString("MM/dd/yyyy");
IEnumerable<SWFSalesModel> arrLastYearSales = GetLastYearsSalesData(o_Cache, cacheKey);
I've also tried it referencing the memory cache in the function as such:
private static IEnumerable<SWFSalesModel> GetLastYearsSalesData(string cacheKey) {
ObjectCache o_Cache = MemoryCache.Default;
....
}
There is something that I obviously don't understand and would appreciate anyone's assistance on this immensely!