【发布时间】:2010-11-21 02:51:27
【问题描述】:
我创建了一个超级简单的控制台应用程序来测试企业库缓存应用程序块,其行为令人费解。我希望我搞砸了一些容易在设置中修复的东西。出于测试目的,我让每个项目在 5 秒后过期。
基本设置——“每秒选择一个介于 0 和 2 之间的数字。如果缓存中还没有它,则将其放入其中——否则只需从缓存中获取它。在 LOCK 语句中执行此操作以确保线程安全。
APP.CONFIG:
<configuration>
<configSections>
<section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<cachingConfiguration defaultCacheManager="Cache Manager">
<cacheManagers>
<add expirationPollFrequencyInSeconds="1" maximumElementsInCacheBeforeScavenging="1000"
numberToRemoveWhenScavenging="10" backingStoreName="Null Storage"
type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Cache Manager" />
</cacheManagers>
<backingStores>
<add encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Null Storage" />
</backingStores>
</cachingConfiguration>
</configuration>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
namespace ConsoleApplication1
{
class Program
{
public static ICacheManager cache = CacheFactory.GetCacheManager("Cache Manager");
static void Main(string[] args)
{
while (true)
{
System.Threading.Thread.Sleep(1000); // sleep for one second.
var key = new Random().Next(3).ToString();
string value;
lock (cache)
{
if (!cache.Contains(key))
{
cache.Add(key, key, CacheItemPriority.Normal, null, new SlidingTime(TimeSpan.FromSeconds(5)));
}
value = (string)cache.GetData(key);
}
Console.WriteLine("{0} --> '{1}'", key, value);
//if (null == value) throw new Exception();
}
}
}
}
OUTPUT -- 如何防止缓存返回空值?
2 --> '2'
1 --> '1'
2 --> '2'
0 --> '0'
2 --> '2'
0 --> '0'
1 --> ''
0 --> '0'
1 --> '1'
2 --> ''
0 --> '0'
2 --> '2'
0 --> '0'
1 --> ''
2 --> '2'
1 --> '1'
Press any key to continue . . .
【问题讨论】:
-
总之,Caching Application Block“以线程安全的方式执行”。
-
看来,如果项目过期, Contains() 只会返回 true。但是 GetData() 在这种情况下返回 null。如果将该条件更改为 if ((value = GetData(...)) == null) 一切正常
标签: c# .net caching thread-safety enterprise-library