dcp
dcp

Reputation: 55424

C# HttpRuntime.Cache

I am on Win7 64-bit. This is a rather nasty problem. Here are the steps to reproduce it:

  1. Create a new C# Asp.Net project in Visual Studio (I'm using VS 2010, not sure if this matters)

  2. In the code behind for Default.aspx, add this code to the Page_Load method

    HttpRuntime.Cache.Insert("foo", "test", null, DateTime.Now.AddMinutes(30), TimeSpan.FromMinutes(0));
    
    string p = "var retval; retval = window.showModalDialog('Test.aspx','', 'dialogHeight:100px; dialogWidth: 100px;scroll: no;center: Yes; help: No; resizable: yes; status: no; unadorned: yes;');";
    ScriptManager.RegisterStartupScript(this, GetType(), "openpop", p, true);
    
  3. Add another Web Form called Test.aspx. You can put whatever you want in the markup, it's not important.

  4. In the code behind for Test.aspx, put this line in the Page_Load method, and set a breakpoint on it.

    string x = (string)HttpRuntime.Cache["foo"];
    
  5. In the project properties, make sure application is set to run using local IIS Web Server.

When you run the project and it hits the breakpoint, step one more time to let it assign x, and then the value of x will be null. At least that's what's happening to me. I don't understand why this is happening, because the value should still be in the cache. In my real application, I also added a callback to HttpRuntime.Cache.Insert to track why the item was not in the cache, and it said it had expired. But if I gave it a 30 minute absolute expiration window, how can it be expired?

Interestingly enough, if you run the application using Visual Studio Development Server instead of IIS, the value is present in the cache!

Upvotes: 0

Views: 2710

Answers (1)

Lanorkin
Lanorkin

Reputation: 7504

I don't have any issues with such setup, but you do. So I think the issue is in DateTime.Now setting you use. According to msdn:

The time at which the inserted object expires and is removed from the cache. To avoid possible issues with local time such as changes from standard time to daylight saving time, use UtcNow rather than Now for this parameter value. If you are using absolute expiration, the slidingExpiration parameter must be NoSlidingExpiration.

So try this one:

HttpRuntime.Cache.Insert("foo", "test", null, DateTime.UtcNow.AddMinutes(30), TimeSpan.FromMinutes(0));

Upvotes: 4

Related Questions