【发布时间】:2013-04-09 20:31:13
【问题描述】:
我目前正在.net 4 中开发一个 Windows 服务。它连接到一个 WS,它发回我需要的信息。 我使用一个计时器:每隔 x 秒,服务会向网络服务询问信息。但是为了避免每次都访问 WS,我想将这些凭据存储在缓存中。
我用谷歌搜索并没有找到任何与 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 是好用的类吗?
在 [another post][1] 中,他们建议使用 ASP.NET Cache (System.Web.Caching),但在 Windows 服务中这似乎很奇怪,不是吗?
如果您能指导我一点,将不胜感激。
编辑
我将new DateTimeOffset(0, 0, 1, 0, 0, 0, new TimeSpan(1, 0, 0, 0)) 更改为new DateTimeOffset(DateTime.UtcNow.AddHours(24)) 没有区别 效果很好!
【问题讨论】:
标签: c# caching windows-services