user766237
user766237

Reputation: 25

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. Here is the code that I'm using from MSDN docs:

           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.

The surprising thing is I have a wrapper C# 4.0 assembly that I'm consuming from QTP and it is working absolutely good. The cache stays on each run in QTP.

Please help.

Upvotes: 1

Views: 618

Answers (1)

Jay
Jay

Reputation: 57919

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."

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.

Only if your application runs for more than an hour would that policy have any effect.

Upvotes: 1

Related Questions