我目前正在.NET 4中开发一个Windows服务。它连接到一个WS,它发回我需要的信息。 我使用一个计时器:每x秒,服务询问web服务的信息。但为了避免每次访问WS,我想将这些凭据存储在缓存中。Windows服务和缓存
我搜索了一下,没有发现任何与Windows服务情况相关的东西(它总是关于ASP.NET环境)。
我试过MemoryCache
(从ObjectCache
从System.Runtime.Caching
)没有成功。 这是我的课我使用缓存。
我是好的还是完全错的?
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;
}
}
是MemoryCache
是不是很好用的类?
在[另一篇文章] [1]中,他们建议ASP.NET缓存(System.Web.Caching
),但在Windows服务中似乎很奇怪,不是吗?
如果你能指导我一点,它将不胜感激。
编辑
我通过new DateTimeOffset(DateTime.UtcNow.AddHours(24))
改变和它完美的作品!new DateTimeOffset(0, 0, 1, 0, 0, 0, new TimeSpan(1, 0, 0, 0))
没有区别
[1]:Caching for .NET (not in websites)强调文本
这是同样的问题:http://stackoverflow.com/questions/6059860/memorycache-add-returns-true-but-does-not-add-item-to-cache – 2013-04-09 11:45:33