-2

我不确定这种行为是否是由于应用程序(控制台应用程序)的性质造成的。我的最终目标是使用System.Runtime.Caching.MemoryCache将在 ASP.Net MVC 应用程序中使用的类库中的类。目标是从 MemoryCache 返回数据,每次网络文件夹上的 XML 文件(数据源)更改时都会填充该数据。

所以为了实现我的实现,我编写了一个简单的控制台应用程序,其中包含一个List<>将被缓存的对象。这是代码。

using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using CachePersons.Core.Logging;

namespace CachePersons
{
    class Program
    {
        static void Main(string[] args)
        {
            GetPersons();
            GetPersons();
            GetPersons();

            Console.ReadKey();
        }

        static List<string> GetPersons()
        {
            List<string> persons;

            Log.Debug("Entered GetPersons()");
            Console.WriteLine("Entered GetPersons()");

            //get default cache
            ObjectCache cache = MemoryCache.Default;

            //get persons
            persons = (List<string>)cache.Get("Persons");

            //if cache does not contain the persons, create new list and add it to cache
            if (persons == null)
            {
                persons = GetPersonsFromDatabase();

                cache.Add("Persons", persons, new CacheItemPolicy());
            }
            else
            {
                Log.Debug("    Found Data in Cache!");
                Console.WriteLine("    Found Data in Cache!");
            }

            Log.Debug("Exited GetPersons()");
            return persons;
        }

        static List<string> GetPersonsFromDatabase()
        {
            Log.Debug("    Populating Cache 1st time.");
            Console.WriteLine("    Populating Cache 1st time.");
            return new List<string>()
            {
                "John Doe",
                "Jane Doe"
            };
        }

    }
}

然后我构建了项目并打开了 2 个单独的命令窗口,然后一个接一个地运行。我期望(ed)在 DebugView 控制台输出上看到的是,只有 1 次缓存将被填充,并且第二次 .exe 调用将在缓存中找到数据,并从那里返回. 但事实并非如此。请参阅下面来自控制台和调试视图的屏幕截图。

在此处输入图像描述

并在调试视图中...

在此处输入图像描述

我究竟做错了什么?这是因为我使用的是控制台应用程序吗?如何让缓存跨类库中的方法调用工作?如果在 Web 应用程序中使用相同的库(IIS 7.5 上的 ASP.Net MVC),我还需要注意哪些注意事项。

谢谢!

4

1 回答 1

0

您可能会发现内存映射文件很有帮助。

PS:如果您打算在 IIS 上运行您的应用程序。您的原始代码应该没问题。

于 2014-03-12T20:08:05.090 回答