Accessing HttpRuntime.Cache from other Thread

1.3k views Asked by At

I have a thread running behind my ASP.Net. In this thread I put data in the cache like this:

HttpRuntime.Cache.Insert("test", "test", null, DateTime.Today.AddHours(6), Cache.NoSlidingExpiration);   

On the other thread(the webpage) I first check if the cache contains any data, and then try to get the object from the cache, like this:

 if (HttpRuntime.Cache.Count > 0) {
          var test = (string)HttpRuntime.Cache["test"];
 }

Edit: Everytime when I'm trying to do var test = (string)HttpRuntime.Cache["test"];the cache will go empty(or will delete the object, haven't tested multiple objects in cache) plus the var test is also null. This is ofcourse when HttpRuntime.Cache.Count is bigger than 0

Oh and it gives no exceptions or anything

2

There are 2 answers

0
Turbot On BEST ANSWER

There is a potential inconsistent in your code that DateTime.Today.AddHours(6) that will not work. you should use DateTime.Now.AddHours(6)

DateTime.Today is current day starting 12:00 AM , if you code runs after 6:00 AM obviously the httpruntime cache isn't available.

0
Aghilas Yakoub On

The Cache object in .NET is thread safe, so get data by thread is not necessary. You can view this article: http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx.

adjust your duration: DateTime.Now.AddHours(6)