我为 .NET MemoryCache 编写了自己的自定义更改监视器类。它似乎初始化得很好,但是当我尝试将它添加到缓存时,它会抛出一个InvalidOperation
异常 -The method has already been invoked, and can only be invoked once.
我的变更监视器类:
internal class MyChangeMonitor : ChangeMonitor
{
private Timer _timer;
private readonly string _uniqueId;
private readonly TypeAsOf _typeAsOf;
private readonly string _tableName;
public GprsChangeMonitor(TypeAsOf typeAsOf, string tableName)
{
bool initComplete = false;
try
{
_typeAsOf = typeAsOf;
_tableName = tableName;
_uniqueId = Guid.NewGuid().ToString();
TimeSpan ts = new TimeSpan(0, 0, 5, 0, 0);
_timer = new Timer {Interval = ts.TotalMilliseconds};
_timer.Elapsed += CheckForChanges;
_timer.Enabled = true;
_timer.Start();
initComplete = true;
}
finally
{
base.InitializationComplete();
if(!initComplete)
Dispose(true);
}
}
void CheckForChanges(object sender, System.Timers.ElapsedEventArgs e)
{
//check for changes, if different
base.OnChanged(_typeAsOf);
}
}
我用来创建缓存策略并将键/值对添加到缓存中的代码:
CacheItemPolicy policy = new CacheItemPolicy
{
UpdateCallback = OnCacheEntryUpdateCallback
};
policy.AbsoluteExpiration = SystemTime.Today.AddHours(24);
//monitor the for changes
string tableName = QuickRefreshItems[type];
MyChangeMonitor cm = new MyChangeMonitor(typeAsOf, tableName);
policy.ChangeMonitors.Add(cm);
cm.NotifyOnChanged(OnRefreshQuickLoadCacheItems);
MyCache.Set(cacheKey, value, policy);
该Set
调用抛出了无效的操作异常,这很奇怪,因为根据 MSDN 文档,它只抛出ArgumentNull
、Argument
、ArgumentOutOfRange
和NotSupported
异常。
我确信我一定犯了一个简单的错误。但是很难找到关于编写自己的自定义更改监视器的好的文档或示例。任何帮助,将不胜感激。