I'm currently developing a windows service in .net 4. It connects to a WS which send back the info I need. I use a timer: every x seconds, the service asks the webservice the info. But to avoid accessing WS at each elapse, I would like to store these credentials in cache.
I googled and do not find anything relevant for the Windows Service situation (it's always about ASP.NET environment).
I've tried MemoryCache
(from ObjectCache
from System.Runtime.Caching
) without success.
Here is my class I use the cache.
Am I a in the good way or completely wrong ?
public class Caching
{
private const string CST_KEY = "myinfo";
private const string CST_CACHENAME = "mycache";
private MemoryCache _cache;
public Caching()
{
_cache = new MemoryCache(CST_CACHENAME);
}
private CacheItemPolicy CacheItemPolicy
{
get
{
return new CacheItemPolicy
{
SlidingExpiration = new TimeSpan(1, 0, 0, 0),
AbsoluteExpiration = new DateTimeOffset(0, 0, 1, 0, 0, 0, new TimeSpan(1, 0, 0, 0))
};
}
}
public bool SetClientInformation(ClientInformation client_)
{
if (_cache.Contains(CST_KEY))
_cache.Remove(CST_KEY);
return _cache.Add(CST_KEY, client_, CacheItemPolicy);
}
public bool HasClientInformation()
{
return _cache.Contains(CST_KEY);
}
public ClientInformation GetClientInformation()
{
return _cache.Contains(CST_KEY) ? (ClientInformation) _cache.Get(CST_KEY) : null;
}
}
Is MemoryCache
the good class to use ?
In [another post][1], they suggest ASP.NET Cache (System.Web.Caching
), but it seems weird in a Windows Service, isn't it ?
If you could guide me a bit, it would be appreciated.
Edit
I changed new DateTimeOffset(0, 0, 1, 0, 0, 0, new TimeSpan(1, 0, 0, 0))
by new DateTimeOffset(DateTime.UtcNow.AddHours(24))
without difference and it works perfectly !
[1]: Caching for .NET (not in websites)emphasized text