views:

193

answers:

2

Although i have specified a unique key, it seems the following code will return one value for 5 requests, then another for the next couple, then revert back to the value saved in the original request and just continue until there are 10's of different objects all stored under the same key. It then seems almost random which of these values it will return from the cache.

string strDateTime = string.Empty;
string cachename = "datetimeexample";
object cachedobject = HttpRuntime.Cache.Get(cachename);
if (cachedobject != null)
    strDateTime = (string)cachedobject;
else
{
    strDateTime = DateTime.Now.ToString();
    HttpRuntime.Cache.Insert(cachename, strDateTime, null, DateTime.MaxValue, TimeSpan.FromDays(10), CacheItemPriority.NotRemovable, null);
}
Response.Write(strDateTime +"        keys:"+ HttpRuntime.Cache.Count);

Very confused, is this because of threading or something?

A: 

Your cachekey is always 'datetimeexample', therefore, you will always have one object in cache; and you will always receive that object back.

I am not quite sure what you are trying to accomplish here, as far as I'm concerned, this behaves exactly in the way it's supposed to do.

Jan Jongboom
I want to retrieve the object i originally cached on the first page request, in subsequent requests.
maxp
I cannot reproduce your problems, as this seems perfectly fine. Guess this should be something in your IIS settings.
Jan Jongboom
So your app will just add x1 key and continually retrieve that same key?
maxp
sorry meant datetime string not key
maxp
I created a simple website in VS2008, added the code there, and everything works like a charm.
Jan Jongboom
On a simple page it will do the same for me, its only on the heavier pages that it duplicates.
maxp
+1  A: 

Ignoring the possibility of a server farm and load balancing, this behaviour can be caused by the application pool running as a web-garden. To quote the relevant section from MSDN:

Because Web gardens enable the use of multiple processes, each process will have its own copy of application state, in-process session state, caches, and static data. Web gardens should not be used for all applications, especially if they need to maintain state. Be sure to benchmark the performance of the application before deciding whether Web garden mode is appropriate.

This will cause it to appear as if caching is storing multiple values for the same key, effectively having duplicate entries in the cache.

To resolve this in IIS 7, open the application pool's Advanced Settings and set Maximum Worker Processes to 1. For IIS 6, see the MSDN article (With pretty screenshots).

Albeit 8 months late, I'm answering this question because I found it long before I found this decent article on web-garden gotchas. Hopefully this answer will save future searchers a chunk of time. :)

Zelphar