我有自定义缓存依赖
class MyCacheDependency : CacheDependency
{
private const int PoolInterval = 5000;
private readonly Timer _timer;
private readonly string _readedContent;
public MyCacheDependency()
{
_timer = new Timer(CheckDependencyCallback, this, PoolInterval, PoolInterval);
_readedContent = ReadContentFromFile();
}
private void CheckDependencyCallback(object sender)
{
lock (_timer)
{
if (_readedContent != ReadContentFromFile())
{
NotifyDependencyChanged(sender, EventArgs.Empty);
}
}
}
private static string ReadContentFromFile()
{
return File.ReadAllText(@"C:\file.txt");
}
protected override void DependencyDispose()
{
if (_timer != null) _timer.Dispose();
base.DependencyDispose();
}
}
它完美无缺,但我想知道如何一次刷新所有对象。在这里我放入缓存2个对象
Cache.Insert(“c1”,“var1”,new MyCacheDependency());
Cache.Insert(“c2”,“vae2”,new MyCacheDependency());
很好,但是当c1会检测到更改时如何强制c2不要等待5秒来检查但我想在c1执行时调用自己的DependencyDispose。
换句话说,如果c1检测到变化,c2也应该调用DependencyDispose
答案 0 :(得分:1)
也许你可以在CheckDependencyCallback()方法中添加一个静态事件。在MyCacheDependency的构造函数中,您将附加一个事件处理程序。当事件被触发时,你可以从那里调用NotifyDependencyChanged或DependencyDispose。这样,所有MyCacheDependency对象都会对更改做出反应。
class MyCacheDependency : CacheDependency
{
private const int PoolInterval = 5000;
private readonly Timer _timer;
private readonly string _readedContent;
public static event EventHandler MyEvent;
public MyCacheDependency()
{
_timer = new Timer(CheckDependencyCallback, this, PoolInterval, PoolInterval);
_readedContent = ReadContentFromFile();
MyEvent += new EventHandler(MyEventHandler);
}
protected void MyEventHandler(object sender, EventArgs e) {
NotifyDependencyChanged(sender, e);
}
private void CheckDependencyCallback(object sender)
{
lock (_timer)
{
if (_readedContent != ReadContentFromFile())
{
if(MyEvent!=null)
MyEvent(sender, EventArgs.Empty);
}
}
}
private static string ReadContentFromFile()
{
return File.ReadAllText(@"C:\file.txt");
}
protected override void DependencyDispose()
{
if (_timer != null) _timer.Dispose();
base.DependencyDispose();
}
}