【发布时间】:2010-11-06 11:58:54
【问题描述】:
企业库的文档说:
因为Cache对象的操作方式,保证你 将调用任何后备存储 以单线程方式。这 意味着你不必让你的 实现线程安全。
关于 CacheManager :
通过 CacheManager 对象是线程安全的。
但一个简单的测试证明相反:
这是我的自定义后备存储(只有 Add 方法是相关的)
public class MyStore : IBackingStore
{
volatile bool isEntered = false;
#region IBackingStore Members
public void Add(CacheItem newCacheItem)
{
if(isEntered)
throw new NotImplementedException();
isEntered = true;
Thread.Sleep(1000);
isEntered = false;
}
public int Count
{
get
{
throw new NotImplementedException();
}
}
public void Flush()
{
throw new NotImplementedException();
}
public System.Collections.Hashtable Load()
{
return new System.Collections.Hashtable();
}
public void Remove(string key)
{
throw new NotImplementedException();
}
public void UpdateLastAccessedTime(string key, DateTime timestamp)
{
throw new NotImplementedException();
}
#endregion
#region IDisposable Members
public void Dispose()
{
throw new NotImplementedException();
}
#endregion
}
这是一个通过两个不同线程访问同一个 CacheManager 的测试:
DictionaryConfigurationSource configSource = new DictionaryConfigurationSource();
CacheManagerSettings cacheSettings = new CacheManagerSettings();
configSource.Add(CacheManagerSettings.SectionName, cacheSettings);
CacheStorageData storageConfig = new CacheStorageData("MyStorage", typeof(MyStore));
cacheSettings.BackingStores.Add(storageConfig);
CacheManagerData cacheManagerData = new CacheManagerData("CustomCache", 120, 100, 5, storageConfig.Name);
cacheSettings.CacheManagers.Add(cacheManagerData);
cacheSettings.DefaultCacheManager = cacheManagerData.Name;
CacheManagerFactory cacheFactory = new CacheManagerFactory(configSource);
ICacheManager cacheManager = cacheFactory.CreateDefault();
Thread thread = new Thread(() =>
{
cacheManager.Add("item1", "odaiu");
});
thread.Start();
cacheManager.Add("item2", "dzaoiudoiza");
Add 方法在两个不同的线程中执行两次(因为它抛出了 Add 方法的“NotImplementedException”)。
是我的代码有问题还是企业库的文档有问题?
【问题讨论】:
标签: .net caching enterprise-library