Lazy<T> with expiration time

lazy synonym
lazy meaning
lazy synonyms slang
lazy in spanish
another word for lazy person
ineffective lazy
how to pronounce lazy
most lazy

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 :

NEW EDIT :

the new code :

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;
        }
    }

}

I agree with the other commenters that you probably shouldn't touch Lazy at all. Lazy isn't very complicated if you ignore the multiple thread-safety options, so just implement it from scratch.

I quite like the idea by the way, although I don't know if I'd be comfortable using it as a general purpose caching strategy. It might be sufficient for some of the simpler scenarios.

Here's my stab at it. If you don't need it to be thread-safe you can just remove the locking stuff. I don't think it's possible to use the double-checking lock pattern here because of the chance that the cached value may be be invalidated inside the lock.

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;
            }
        }
    }
}

Lazy Synonyms, Lazy Antonyms, (of a livestock brand) placed on its side rather than upright. 32 synonyms of lazy from the Merriam-Webster Thesaurus, plus 64 related words, definitions, and antonyms. Find another word for lazy. Lazy: not easily aroused to action or work.

I don't think Lazy<T> 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<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;
    }
}

To use, you'd then just use Timed<MyClass> obj = new Timed<MyClass>(); 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<T> because you're essentially forcing a delayed initialization already. You could of course define the maximum lifetime in the constructor for example.

Lazy, Lazy definition is - disinclined to activity or exertion : not energetic or vigorous. How to use lazy in a sentence. Synonym Discussion of lazy. Define lazy. lazy synonyms, lazy pronunciation, lazy translation, English dictionary definition of lazy. adj. la·zi·er , la·zi·est 1. Not willing to work or be energetic. 2.

I needed the same thing. But I would prefer an implementation without locked reads when there is no write.

public class ExpiringLazy<T>
{
    private readonly Func<T> factory;
    private readonly TimeSpan lifetime;
    private readonly ReaderWriterLockSlim locking = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

    private T value;
    private DateTime expiresOn = DateTime.MinValue;

    public ExpiringLazy(Func<T> factory, TimeSpan lifetime)
    {
        this.factory = factory;
        this.lifetime = lifetime;
    }

    public T Value
    {
        get
        {
            DateTime now = DateTime.UtcNow;
            locking.EnterUpgradeableReadLock();
            try
            {
                if (expiresOn < now)
                {
                    locking.EnterWriteLock();
                    try
                    {
                        if (expiresOn < now)
                        {
                            value = factory();
                            expiresOn = DateTime.UtcNow.Add(lifetime);
                        }
                    }
                    finally
                    {
                        locking.ExitWriteLock();
                    }
                }

                return value;
            }
            finally
            {
                locking.ExitUpgradeableReadLock();
            }
        }
    }
}

Lazy Synonyms, Lazy Antonyms, The words indolent and slothful are common synonyms of lazy. While all three words mean "not easily aroused to activity," lazy suggests a  Lazy definition, averse or disinclined to work, activity, or exertion; indolent. See more.

LAZY, Lazy definition, averse or disinclined to work, activity, or exertion; indolent. See more. not willing to work or use any effort: Managers had complained that the workers were lazy and unreliable. Get out of bed, you lazy thing! He's too lazy to walk to work.

lazy, Synonyms for lazy at Thesaurus.com with free online thesaurus, antonyms, and definitions. Find descriptive alternatives for lazy. In short, he is being lazy if his motivation to spare himself effort trumps his motivation to do the right or expected thing. Synonyms for laziness are indolence and sloth. Indolence derives from

lazy, AdjectiveEdit. lazy (comparative lazier, superlative laziest). Unwilling to do work or make an effort; disinclined to exertion. quotations ▽. Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program. To prepare for lazy initialization, you create an instance of Lazy<T>.

Comments
  • Please show the code you currently have for Lazy loading. SO is not a place where we write all the code for you... show what you have tried so far.
  • Extensions and partial keyword I don't think are going to help you here. I would just make a wrapper class for the Lazy<T> (though there is probably a more elegant solution).
  • I agree this is a simple problem, just wrap the accessor with code that checks to see if the timer has expired. I don't think Lazy<T> is needed, but that would change depending on context so please show the code so far.
  • Why do you need it anyway? Just interested in the reason!
  • Could think of many things like a simple cache solution. E.g. reretrieve some RSS feed by recreating the handling object if some time has passed.
  • I believe you need to restrict T to where T : new() in this case.
  • Hm, not really sure. Don't think I've ever used generics in C#. Edit: Yes, seems like you're right.
  • Also, return object is a compile error. You meant return init right? And get would be better suited as a property. The effect is the same, but it's more idiomatic that way.
  • For that matter, the void parameter list is not valid C# either.
  • return object has been a leftover, forgot about the built in type at first and forgot to change that line. void, you're right. As for a getter... what to name it? But yes, lots of different approaches. You could as well skip the whole get() and just wrap all members using some predefined interface as well.