tags:

views:

54

answers:

3

Hello,

What is the best way to hold an object in the memory for a limited period of time, then to free it? For example, I have a Dictionary<int, string> and I want to keep it for 10 minutes only, and after then to dispose it.

How to do that?

Thanks.

+3  A: 

You cannot dispose dictionaries, only the garbage collector gets rid of them. Setting the dictionary reference to null in a timer's Tick event would get the job done, eventually. Look at the WeakReference class.

Hans Passant
Correct,t but my intention wasn't to "Dispose" it, but to not hold it in memory anymore. The terminology wasn't correct.
NewB
+1  A: 

you can use the object cache class (framework 4) according ms documentation is defined this way: public abstract class ObjectCache : IEnumerable>, IEnumerable

The class belogs to System.Runtime.Caching. In order to Use it you have inherit it into a concrete implementation.

This object works in the same way the httpcache application works, so you can define lets say a sliding expiration and/also an absolute expiration time as well

eloycm
Can you please show code example?
NewB
ObjectCache cache = MemoryCache.Default; string fileContents = cache["filecontents"] as string; if (fileContents == null) { CacheItemPolicy policy = new CacheItemPolicy(); List<string> filePaths = new List<string>(); filePaths.Add("c:\\cache\\example.txt"); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); // Fetch the file contents.fileContents = File.ReadAllText("c:\\cache\\example.txt"); cache.Set("filecontents", fileContents, policy); }
eloycm
+1  A: 
  1. Use the Caching Application Block:

    • Define the cach object:

    ICacheManager cacheManager;

    • Insert the dictionary to the cache:

    cacheManager = CacheFactory.GetCacheManager(); cacheManager.Add("sampleDictionary", sampleDictionary, CacheItemPriority.Normal, null, new AbsoluteTime(DateTime.Now.AddMinutes(10)));

    • Retreive the dictionary from the cache:

    Dictionary sampleDictionary = cacheManager.GetData("sampleDictionary") as Dictionary;

  2. Use ASP.NET Caching:

    • Insert the dictionary to the cache:

    HttpRuntime.Cache.Insert("sampleDictionary", sampleDictionary, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);

    • Retreive the dictionary from the cache:

    Dictionary sampleDictionary = HttpRuntime.Cache["sampleDictionary"] as Dictionary;

rursw1