我想在Lazy对象上实现过期时间.到期的冷却时间必须从第一次检索值开始.如果我们得到了值,并且过期时间已经过去,那么我们重新执行该函数并重置到期时间.
我不熟悉扩展,部分关键字,我不知道最好的方法.
谢谢
编辑:
到目前为止的代码:
新编辑:
新代码:
public class LazyWithExpiration<T>
{
private volatile bool expired;
private TimeSpan expirationTime;
private Func<T> func;
private Lazy<T> lazyObject;
public LazyWithExpiration( Func<T> func, TimeSpan expirationTime )
{
this.expirationTime = expirationTime;
this.func = func;
Reset();
}
public void Reset()
{
lazyObject = new Lazy<T>( func );
expired = false;
}
public T Value
{
get
{
if ( expired )
Reset();
if ( !lazyObject.IsValueCreated )
{
Task.Factory.StartNew( () =>
{
Thread.Sleep( expirationTime );
expired = true;
} );
}
return lazyObject.Value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我同意其他评论者的意见,您可能根本不应该接触Lazy。如果您忽略多个线程安全性选项,则惰性并不十分复杂,因此只需从头开始即可实现。
顺便说一句,我很喜欢这个想法,尽管我不知道是否可以将其用作通用缓存策略。对于某些较简单的方案,这可能就足够了。
这是我的目的。如果您不需要它是线程安全的,则只需删除锁定内容即可。我认为这里不可能使用双重检查锁定模式,因为缓存中的值可能会在锁定内失效。
public class Temporary<T>
{
private readonly Func<T> factory;
private readonly TimeSpan lifetime;
private readonly object valueLock = new object();
private T value;
private bool hasValue;
private DateTime creationTime;
public Temporary(Func<T> factory, TimeSpan lifetime)
{
this.factory = factory;
this.lifetime = lifetime;
}
public T Value
{
get
{
DateTime now = DateTime.Now;
lock (this.valueLock)
{
if (this.hasValue)
{
if (this.creationTime.Add(this.lifetime) < now)
{
this.hasValue = false;
}
}
if (!this.hasValue)
{
this.value = this.factory();
this.hasValue = true;
// You can also use the existing "now" variable here.
// It depends on when you want the cache time to start
// counting from.
this.creationTime = Datetime.Now;
}
return this.value;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为Lazy<T>这里不会有任何影响,它更像是一种通用方法,本质上类似于单例模式。
您将需要一个简单的包装类,它将返回真实对象或传递对其的所有调用。
我会尝试这样的事情(内存不足,所以可能包含错误):
public class Timed<T> where T : new() {
DateTime init;
T obj;
public Timed() {
init = new DateTime(0);
}
public T get() {
if (DateTime.Now - init > max_lifetime) {
obj = new T();
init = DateTime.Now;
}
return obj;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用,您只需使用而Timed<MyClass> obj = new Timed<MyClass>();不是MyClass obj = new MyClass();. 实际的调用将obj.get().doSomething()代替obj.doSomething().
编辑:
只是要注意,您不必将类似于我上面的方法结合起来,Lazy<T>因为您实际上已经强制延迟初始化了。例如,您当然可以在构造函数中定义最大生命周期。