我創建了一個超級簡單的控制檯應用程序來測試企業庫緩存應用程序塊,行爲令人困惑。我希望我搞定了一些在設置中很容易修復的東西。爲了測試目的,我將每個項目在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