我在Windows 7上运行VS 2010 Ultimate并尝试使用MemoryCache(System.Runtime.Caching),出于某种原因,当方法结束并重新运行时,缓存立即清除该方法再次,它试图创建一个新的。这里是我使用从MSDN文档代码:奇怪的MemoryCache类问题
ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"] as string;
if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
List<string> filePaths = new List<string>();
filePaths.Add("c:\\Windows\\Enterprise.xml");
// policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));
policy.Priority = CacheItemPriority.NotRemovable;
policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(3600);
// Fetch the file contents.
fileContents =
File.ReadAllText("c:\\Windows\\Enterprise.xml");
cache.Set("filecontents", fileContents, policy);
}
Console.WriteLine(fileContents);
我在控制台Main方法中有此代码。
令人惊讶的是我有一个包装C#4.0程序集,我从QTP中使用,它工作得非常好。缓存保留在QTP的每次运行中。
请帮忙。
所以如果这是在Main方法中,程序在这之后关闭还是进入循环? –
控件退出该方法并停止调试器。但是,当我以调试模式再次运行该方法时,它会看到缓存为空并进入if子句。 Visual Studio IDE仍处于开放状态。我假设缓存应该保留,因为我的过期时间设置为1小时,并且不可移除。 – user766237
我认为问题在于,虽然您已将其设置为一小时而不可移除;你从静态方法中这样做,这意味着当调试器分离并且垃圾收集时缓存的上下文消失。我只是理论,虽然... –