gpt4 book ai didi

c# - Custom ChangeMonitor for .Net MemoryCache 导致无效操作异常

转载 作者:太空狗 更新时间:2023-10-29 18:30:06 24 4
gpt4 key购买 nike

我已经为 .NET MemoryCache 编写了自己的自定义更改监视器类。它似乎初始化很好,但是当我试图将它添加到缓存时,它抛出一个 InvalidOperation 异常 - 该方法已经被调用,并且只能被调用一次。

我的变更监控类:

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 文档,它只会抛出 ArgumentNullArgumentArgumentOutOfRangeNotSupported 异常。

我确信我一定犯了一个简单的错误。但是很难找到关于编写您自己的自定义更改监视器的好的文档或示例。任何帮助将不胜感激。

最佳答案

我知道评论有答案,但我希望它更明显...

当使用 ChangeMonitor 时,如果缓存条目不存在,它将立即触发。
MSDN documentation states it this way :

A monitored entry is considered to have changed for any of the following reasons:

A) The key does not exist at the time of the call to the CreateCacheEntryChangeMonitor method. In that case, the resulting CacheEntryChangeMonitor instance is immediately set to a changed state. This means that when code subsequently binds a change-notification callback, the callback is triggered immediately.

B) The associated cache entry was removed from the cache. This can occur if the entry is explicitly removed, if it expires, or if it is evicted to recover memory

关于c# - Custom ChangeMonitor for .Net MemoryCache 导致无效操作异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5518015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com