Lazy with expiration time

前端 未结 3 681
春和景丽
春和景丽 2021-02-13 21:29

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

3条回答
  •  一向
    一向 (楼主)
    2021-02-13 21:47

    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 obj = new 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.

提交回复
热议问题