Sunday, 8 September 2013

Lazy with expiration time

Lazy with expiration time

I want to implement an expiration time on a Lazy object. The expiration
cooldown must start with the first retrieve of the value. If we get the
value, and the expiration time is passed, then we reexecute the function
and reset expiration time.
I'm not familiar with extensions, partial keyword, and I don't know the
best way to do that.
Thanks
EDIT :
The code so far :
public class LazyWithExpiration<T> : Lazy<T>
{
private volatile bool expired = false;
private TimeSpan expirationTime;
public LazyWithExpiration(Func<T> func, TimeSpan expirationTime) :
base(func)
{
this.expirationTime = expirationTime;
}
public T Value
{
get
{
if ( expired )
{
base.??? //Reset the state of the lazy object
expired = false;
}
if ( !base.IsValueCreated )
{
Task.Factory.StartNew( () =>
{
Thread.Sleep( expirationTime );
expired = true;
} );
}
return base.Value;
}
}

No comments:

Post a Comment