Only Microsoft knows why their preferred way for caching only works with ASP.NET.
But it’s a fact that the class System.Web.Caching.Cache only works in a web environment.
If you want to cache application data for a windows application you have to write your own caching code.
Due to the fact that I like the Cache class for ASP. NET I re-wrote it in order to use it for Windows Applications.
The benefit of that implementation is that you can specify an expiration date for the cached object.
public void Insert(string key, object current, DateTime absoluteExpiration, TimeSpan slidingExpiration)
Example:
class Program
{
private static Cache cache = new Cache();
/// <summary>
/// Caching test
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
BigObjectForCaching bof = new BigObjectForCaching();
bof.Content = "Imagine that this is a very big objectyou want to cache.";
Console.WriteLine("Insert Bof01 with a 5 second sliding expiration into cache.");
/*
* Take 5 seconds into cache (use sliding cache expiration)
*/
cache.Insert("bof01", bof, Cache.NoAbsoluteExpiration, new TimeSpan(0,0,0,5));
/*
* Loop 10 seconds to show the cache change
*/
for (int x = 0; x < 10; x++)
{
Console.WriteLine(string.Concat("Bof01 is in cache ", cache.Contains("bof01")));
Thread.Sleep(1000);
}
Console.WriteLine("\nInsert Bof01 with a 5 second static expiration into cache.");
/*
* Insert object into cache. Use static expiration
*/
cache.Insert("bof01", bof, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration);
/*
* Loop 10 seconds to show the cache change
*/
for (int x = 0; x < 10; x++)
{
Console.WriteLine(string.Concat("Bof01 is in cache ", cache.Contains("bof01")));
Thread.Sleep(1000);
}
/*
* Insert last time into cache - object never expires
*/
cache.Insert("bof01", bof, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
bof = cache.Get("bof01") as BigObjectForCaching;
Console.WriteLine(string.Concat("\nContent : ", bof.Content));
Console.ReadKey();
}
/*
* Expected output :
*
* Insert Bof01 with a 5 second sliding expiration into cache.
*
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache False
* Bof01 is in cache False
* Bof01 is in cache False
* Bof01 is in cache False
* Bof01 is in cache False
*
* Insert Bof01 with a 5 second static expiration into cache.
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache True
* Bof01 is in cache False
* Bof01 is in cache False
* Bof01 is in cache False
* Bof01 is in cache False
* Bof01 is in cache False
*
* Content : Imagine that this is a very big objectyou want to cache.
*/
}
You can download that small example including the re-wroted implementation of the cache class using the following link:
http://www.ad-factum.de/wordpress/CacheTest.zip
Best regards
- Gerhard