【发布时间】:2014-04-17 04:57:49
【问题描述】:
我不确定这种行为是否是由于应用程序(控制台应用程序)的性质造成的。我的最终目标是在将在 ASP.Net MVC 应用程序中使用的类库中使用 System.Runtime.Caching.MemoryCache 类。目标是从每次网络文件夹上的 XML 文件(数据源)更改时填充的 MemoryCache 返回数据。
为了实现我的实现,我编写了一个简单的控制台应用程序,其中包含将被缓存的对象 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 调用将在缓存中找到数据,并从那里返回.但事实并非如此。请参阅下面来自控制台和调试视图的屏幕截图。
在 DebugView 中...
我做错了什么?这是因为我使用的是控制台应用程序吗?如何让缓存跨类库中的方法调用工作?如果在 Web 应用程序中使用相同的库(IIS 7.5 上的 ASP.Net MVC),我还需要注意哪些注意事项。
谢谢!
【问题讨论】:
-
这和你的缓存范围有关。
-
什么意思?你能详细说明一下吗?谢谢。
-
考虑到它是一个内存缓存,这种行为似乎完全合理。如果不在当前进程的数据中,缓存会将其数据存储在哪个内存中?您的 2 个控制台应用程序进程不共享用于存储缓存的公共内存池。
-
好的,我明白了。也在想同样的事情。那么它对 ASP.Net IIS 托管的 Web 应用程序是如何工作的呢?如果我引用具有上述缓存代码的类库,那么从网页对已实现上述缓存的方法的后续调用是否可以访问相同的内存缓存,直到 IIS AppPool 或应用程序被回收?
-
@Shiva 网页在 appdomain 中(相对)恒定的应用程序池中运行。与两个命令行工具相反。每个 appdomain 都有一个静态对象。
标签: c# asp.net performance caching memorycache