1
我正在使用.net 4.0專門System.runtime.caching。 有沒有人有經驗或如何創建自定義changemonitor的例子?.net緩存與system.runtime.caching
我想要做的是,當我的程序啓動時,其執行計數爲1.用戶單擊一個按鈕,將執行計數增加到2,並將數據庫結果加載到緩存中。如果execount遞增到3,那麼我想使緩存無效並將新結果加載到要使用的緩存中。
有沒有人有任何建議如何做到這一點?
- 我一直在這一段時間,並用此來了,但我不知道如果我在正確的軌道上我想要做的(上述)主要是因爲TI無法正常工作。
我有4類文件
Cache.cs:
public static class Cache {
public static void Add(string key, object obj, CacheItemPolicy policy) {
ObjectCache cache = MemoryCache.Default;
cache.Add(key, obj, policy);
}
public static void AddExecCount(string key, object obj) {
Add(key, obj, new ExecCountCacheItemPolicy());
}
public static object Get(string key) {
ObjectCache cache = MemoryCache.Default;
if (cache.Contains(key) == true)
return cache.Get(key);
else
return null;
}
public static void Clear() {
Material.MaterialFamilyList.ClearCache();
Material.UsageMaterialDropList.ClearCache();
}
/// <summary>
/// Clears the in-memory cache so the list matching the provided key is reloaded on next request.
/// </summary>
/// <param name="key"></param>
public static void Clear(string key) {
ObjectCache cache = MemoryCache.Default;
if (cache.Contains(key) == true)
cache.Remove(key);
}
}
然後ExecCountCacheitemPolicy.cs
public class ExecCountCacheItemPolicy : CacheItemPolicy {
public ExecCountCacheItemPolicy() {
this.ChangeMonitors.Add(new ExecCountChangeMonitor());
//ExecCount.Increment();
}
}
ExecCountChangeMonitor.cs
public class ExecCountChangeMonitor : CacheEntryChangeMonitor {
private ReadOnlyCollection<String> _cacheKeys;
private string _uniqueId;
private string _regionName;
private DateTimeOffset _lastModified;
public ExecCountChangeMonitor() {
_uniqueId = "ExecCountChangeMonitor";
_regionName = "";
_lastModified = DateTime.Now;
var keys = new List<string>();
keys.Add(ExecCount.CACHE_KEY);
_cacheKeys = new ReadOnlyCollection<String>(keys);
InitializationComplete();
}
public override string UniqueId {
get { return _uniqueId; }
}
public override ReadOnlyCollection<string> CacheKeys {
get { return _cacheKeys; }
}
public override DateTimeOffset LastModified {
get { return _lastModified; }
}
protected override void Dispose(bool disposing) {
base.Dispose();
}
public override string RegionName {
get { return _regionName; }
}
}
最後ExecCount.cs
public const string CACHE_KEY = "ExecCount";
public static int Value {
get {
ObjectCache cache = MemoryCache.Default;
if (cache.Contains(CACHE_KEY)) {
return (int)cache.Get(CACHE_KEY);
} else {
return 0;
}
}
}
public static int Increment() {
CacheItem item;
ObjectCache cache = MemoryCache.Default;
if (cache.Contains(CACHE_KEY)) {
item = cache.GetCacheItem(CACHE_KEY);
} else {
item = new CacheItem(CACHE_KEY, 0, "");
cache.Add(item, new CacheItemPolicy());
}
item.Value = (int)item.Value + 1;
return (int)item.Value;
}
}
,如果任何機構對爲什麼這是不工作,如果另一種方式可以用來完成同樣的事情,任何的IDE?
此問題可能包含一些有用的信息:http://stackoverflow.com/questions/6664297/caching-in-a-wcf-application/6664440#6664440 –