skip to Main Content

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()
    ...
  }

2

Answers


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

    Login or Signup to reply.
  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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search