【发布时间】:2017-03-16 12:23:52
【问题描述】:
使用 .net 4.6,我有一个 Windows 服务,它有一个每天在配置的时间唤醒的计时器,连接到远程数据库并使用 MemoryCache 类在内存中缓存一些数据:
string id = rec.ID;
string surname = rec.Surname;
string dateOfBirth = rec.DateOfBirth;
string agreement = rec.Agreement;
CachedData cd = new CachedData(id, surname, dateOfBirth, agreement);
MemoryCache.Default.Set(id, cd, new DateTimeOffset(DateTime.Now.AddDays(1)));
我需要在这个 MemoryCache 上公开一个查找接口。我有一个单独的 WCF 服务,它公开了一个查找接口,但我不知道如何在 WCf 服务和 Windows 服务之间传递查找请求/结果,所以如果我在 WCf 服务中获得一个 id:
string id = HttpContext.Current.Request.QueryString.Get("id");
我可以将它传递给 Windows 服务,它会在内存缓存中查找它并返回结果。
我跟随https://msdn.microsoft.com/en-us/library/ff649818.aspx 在windows 服务中托管wcf 服务。最后,我只是在我的 WindowsService 的 Service1.cs 类的 OnStart() 方法中添加了以下内容:
MemoryCache.Default.Set("K", "Hello World", new DateTimeOffset(DateTime.Now.AddDays(1)));
并假设由于 WCF 服务(也称为 Service1.cs)现在由 windows 服务托管并且将共享同一个应用程序域,我将 WCF 中的默认 GetData 方法修改如下:
public string GetData(int value)
{
var kv = MemoryCache.Default["K"] as string;
if (kv != null)
{
return kv;
}
else
{
return string.Format("Entered: {0}", value);
}
}
但是,当我使用测试客户端并调用 GetData 时,它在 MemoryCache 中找不到缓存的项目。
【问题讨论】:
标签: c# web-services wcf windows-services memorycache