我创建了一个超级简单的控制台应用程序来测试企业库缓存应用程序块,行为令人困惑。我希望我搞定了一些在设置中很容易修复的东西。为了测试目的,我将每个项目在5秒后过期。Microsoft企业库缓存应用程序块不是线程安全的?
基本设置 - “每一秒挑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();
}
}
}
}
输出 - 我如何防止返回空值缓存
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 . . .
情况下,[缓存应用程序块(http://msdn.microsoft.com/en-us /library/ff664753%28v=PandP.50%29.aspx)“以线程安全的方式执行”。 – felickz 2012-01-04 16:21:53
看来,如果item已过期,Contains()只会返回true。但GetData()在这种情况下返回null。如果将该条件更改为if((value = GetData(...))== null)一切正常 – 2014-06-17 15:25:31