简体   繁体   English

奇怪的MemoryCache类问题

[英]Weird MemoryCache class issue

I'm running on VS 2010 Ultimate on Windows 7 and trying to use MemoryCache (System.Runtime.Caching) and for some reason, the cache is immediately cleared when the method ends and when I re-run the method again, it is trying to create a new one. 我在Windows 7上的VS 2010 Ultimate上运行,并尝试使用MemoryCache(System.Runtime.Caching),由于某种原因,当方法结束时缓存会立即清除,而当我再次重新运行该方法时,它正在尝试创建一个新的。 Here is the code that I'm using from MSDN docs: 这是我从MSDN文档使用的代码:

           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);

I have this code in the Console Main method. 我在Console Main方法中有此代码。

The surprising thing is I have a wrapper C# 4.0 assembly that I'm consuming from QTP and it is working absolutely good. 令人惊讶的是,我有一个包装的C#4.0程序集,该程序集是我从QTP中使用的,并且运行得非常好。 The cache stays on each run in QTP. 缓存保留在QTP中的每次运行中。

Please help. 请帮忙。

The lifetime of the MemoryCache is not tied at all to Visual Studio (you mentioned in a comment that "Visual Studio IDE is still open." MemoryCache的生存期与Visual Studio完全无关(您在注释中提到“ Visual Studio IDE仍处于打开状态”。

The cache is available only while your program is running, so each time you stop and restart your application the cache will in fact be empty. 缓存仅在程序运行时可用,因此每次停止并重新启动应用程序时,缓存实际上将为空。 More specifically, it resides within the context of an AppDomain , which is created when you start your application and destroyed when your application exits. 更具体地说,它位于AppDomain的上下文中,该上下文在您启动应用程序时创建,并在应用程序退出时销毁。

Only if your application runs for more than an hour would that policy have any effect. 仅当您的应用程序运行一个小时以上时,该策略才会生效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM