2

are there Application variables in ASP.NET? I want to store for all Users an Object which should be independent updated every 5 Minutes. But all users should always see last version of it. Any suggestions (C#)?

csharpnoob
  • 505
  • 1
  • 9
  • 24

2 Answers2

3

You can store application-wide data in the ASP.NET Cache.

Add your item to the cache using the Cache.Insert method. Set the sliding expiration value to a TimeSpan of 5 minutes. Write a wrapper class for accessing the object in the cache. The wrapper class can provide a method to obtain the object from the cache. This method can check whether whether the item is in the cache and load it if it isn't.

For example:

public static class CacheHelper
{
    public static MyObject Get()
    {
        MyObject obj = HttpRuntime.Cache.Get("myobject") as MyObject;

        if (obj == null)
        {
            // Create the object to insert into the cache
            obj = CreateObjectByWhateverMeansNecessary();

            HttpRuntime.Cache.Insert("myobject", obj, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);

        }
        return obj;
    }
}
pmarflee
  • 3,428
  • 20
  • 21
  • @pmarflee, There should not be sliding expiration. Since he wants it updated every 5 minutes. "But all users should always see last version of it", he says. – Çağdaş Tekin Oct 17 '09 at 17:56
  • thanks, i set the time to 5 hours, but after 20 minutes the object was created new again. what did i wrong? i cache per session per user? or when is cache on mvc gone? – csharpnoob Oct 17 '09 at 18:18
  • finally i solved it with application_start() and these caching methods. problem was Lifetime of Workerprocess in IIS, was on 5 minutes. So applcation was always killed and restarted – csharpnoob Oct 17 '09 at 20:48
0

You can use the OutputCacheAttribute for the method in question. It has a duration property.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142