开发者

Saving Values in Session or Cache - Difference? ASP.NET

I'd like to know when exactly I should use the Session and when exactly I should use the cache. Are there differences in performance? Can one of them handle a lot of data better? Should the Cache only be used for stuff that's associated with the Application whilst the Session should only be used for stuff that's associated with the current session/user? Is it wiser to save values which I received from a DB in the Session or the Cache - is there a difference at all assuming I make the cache-keys unique? E.g. Cache["MyKey"+UserId.ToString()].

Also, in general, is using the Session/Cache a lot wiser than retrieving Data from a DB or a Webservice o开发者_StackOverflow社区r is there a limit of data that'll be retrieved quicker?


Some differences between session and cache:

  • The session is per user while the cache is per application
  • You can store the session data out-of-process (SessionServer or SqlServer) e.g. when using a web farm
  • What you put into the session stays there until the session is terminated/abandoned or times-out
  • With the cache, you can specify that items are automatically removed after some time (absolute) or after they were not accessed for some time (sliding)
  • You can also use SqlCacheDependencies to have items removed from the cache when some data changes in a database
  • the ASP.NET runtime will also automatically remove items from the cache if the available memory gets low

As for performance:

  • As long as you use InProc session state, I guess there won't be any performance difference between session and cache.
  • As soon as you use external session state, performance will obviously be lower than the InProc-cache but I don't have any numbers (depends on network, SQL server power, etc).
  • BTW: there are also distributed caching solutions which allow having an external, shared cache (similar to the out-of-process session state).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜