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
I don't think Lazy
would have any influence here, it's more like a general approach, essentially being similar to the singleton pattern.
You'll need a simple wrapper class which will either return the real object or pass all calls to it.
I'd try something like this (out of memory, so might include bugs):
public class Timed 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;
}
}
To use, you'd then just use Timed
rather than MyClass obj = new MyClass();
. And actual calls would be obj.get().doSomething()
instead of obj.doSomething()
.
Edit:
Just to note, you won't have to combine an approach similar to mine above with Lazy
because you're essentially forcing a delayed initialization already. You could of course define the maximum lifetime in the constructor for example.