3

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Timo Hermans
  • 165
  • 2
  • 10
  • Could you clarify "after this line?" Are you saying that in your if statement `Cache.Count > 0`, but sometime during `var test = (string)HttpRuntime.Cache["test"];` it is empty? – Jaime Torres Jul 24 '12 at 15:59
  • 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 that yet) plus the `var test` is also null. This is ofcourse when `HttpRuntime.Cache.Count` is bigger than 0 – Timo Hermans Jul 24 '12 at 16:57

2 Answers2

1

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.

Turbot
  • 5,095
  • 1
  • 22
  • 30
1

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)

dandan78
  • 13,328
  • 13
  • 64
  • 78
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51