18

Possible Duplicate:
Cache v.s Session

I am using some code that uses HttpRuntime.Cache to store a value. However when I close the window the cache goes away. Is there any benefit to using this over Session?

Here is my code:

protected dynamic Code()
{
    dynamic code;

    if (String.IsNullOrEmpty(myHttpContext.Request.QueryString["code"]))
    {
        code = HttpRuntime.Cache["code"];
    }
    else
    {
        code = myHttpContext.Request.QueryString["code"];
        HttpRuntime.Cache.Insert("code", myHttpContext.Request.QueryString["code"]);
    }

    return code;
}

protected string GetAccessToken(bool regenerate = false)
{
    if (HttpRuntime.Cache["access_token"] == null || regenerate == true)
    {
        try
        {
            Dictionary<string, string> args = GetOauthTokens(myHttpContext.Request.QueryString["code"]);
            HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);
        }
        catch
        {
            OutputError("Code", "Bad Verification Code");
        }
    }

    return HttpRuntime.Cache["access_token"].ToString();
}
Community
  • 1
  • 1
Darren
  • 10,631
  • 8
  • 42
  • 64

3 Answers3

25

HttpRuntime.Cache is global for the application; it is shared among all users/sessions of the web site.

Session is unique per user session. What one user session stores in the Session is private to that session. Another session will have its own storage.

Appulus
  • 18,630
  • 11
  • 38
  • 46
Anders Abel
  • 67,989
  • 17
  • 150
  • 217
  • Hi so HttpRuntime.Cache["access_token"] is visible to all users? This is how it was written in the tutorial, this would be a very big security vulnerability then! – Darren Dec 22 '11 at 00:05
  • 1
    Session is also unique per worker thread according to http://stackoverflow.com/questions/2151251/asp-net-web-garden-how-many-worker-processes-do-i-need – Jeff Jun 12 '14 at 15:49
  • 1
    @Jeff. That question states that with normal InProc session storage, `Session` is unique per worker *process*, not per *thread*. The difference is huge - ASP.NET always use many threads, but many processes only when configured so. With multiple worker processes, `Session` should probably be stored out-of-process which is possible. – Anders Abel Jun 13 '14 at 06:49
4

Possibly the reason you are seeing the cache clear down is that you are restarting your web server when you are rerunning your site. This would make it seem like the cache object and session were behaving in the same way when in fact they are very different.

It could be for instance that this happens when using Visual Studio's built in web server i.e. when running the site as a web application.

Just a thought.

Crab Bucket
  • 6,219
  • 8
  • 38
  • 73
1

The Cache object lives in memory only and is global to the application. Objects can be removed from Cache at any time by ASP.NET (although you can influence that to some degree with arguments to Cache.Add()). When the AppPool recycles or shuts down due to inactivity, or if you restart your application (such as by changing web.config), the Cache will also be dropped.

Just closing a web page is not enough by itself to drop the Cache.

The Session object is unique per user session (usually unique per browser instance). At the end of each request, in can either be serialized and stored in SQL Server, or just kept in memory (InProc mode), or serialized and sent to a specialized app called StateServer. If it's stored in memory, it will be lost under the same conditions as Cache. If it's written to SQL Server, then it will be kept until the session expires, even if the AppPool recycles.

Note that the code in your question should use a lock() when reading/updating the Cache object. Otherwise, you have a potential race condition.

RickNZ
  • 18,448
  • 3
  • 51
  • 66