0

I would like to set property for a X minutes. After that period it should return null or expired.

Is there any simple mechanism in C#?

Like this:

  private static TimeCache<LoginData> _session;

  private void Login() {
    ...
    _session.Set(ws.Login());
  }

  private void DoStuff() {
    if (_session.Expired)
      Login()
    ...
  }
GetoX
  • 4,225
  • 2
  • 33
  • 30
  • Not natively, but it wouldn't be too hard to create. – Rufus L Jan 13 '20 at 22:30
  • Since you are using memcached it does so for you just fine - https://stackoverflow.com/questions/967875/memcached-expiration-time... Could you please clarify why that does not work for you? – Alexei Levenkov Jan 13 '20 at 22:31

2 Answers2

2

You can create a simple class for this.

class ExpiringValue<T>
{
    protected T _value;
    protected DateTime _expiration;

    public ExpiringValue(T val, DateTime expiration)
    {
        _value = val;
        _expiration = expiration;
    }

    public T Value => _expiration < DateTime.Now ? default(T) : _value;
}

To use it, you could do something this:

var message = new ExpiringValue<string>("Hello world", DateTime.Now.AddSeconds(10));

Console.WriteLine("The message is set to {0}", message.Value);
John Wu
  • 50,556
  • 8
  • 44
  • 80
0

You can use a Timer event OnTimedEvent to reset your property, but be mindful about the thread safety of your property.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
FooBar
  • 132
  • 1
  • 9