HttpRuntime Cache vs. static dictionary/fields

僤鯓⒐⒋嵵緔 提交于 2019-12-13 11:41:52

问题


What are the main pros and cons for using HttpRuntime Cache against using simple static field?

I need to store data in scope of entire ASP.NET application.

HttpRuntime.Cache["MyData"] = someHashtable;

vs.

private static System.Collections.Hashtable _myData;
public static System.Collections.Hashtable MyData
{
    get
    {
        if (_myData == null)
        {
            _myData = new System.Collections.Hashtable();
            // TODO: Load data
        }
        return _myData;
    }
}

回答1:


Objects in HttpRuntime.Cache have unknown expiry periods unless explicitly set (meaning that objects can expire any time), whereas objects within your HashTable live for as your application pool is alive (unless you manually remove an entry). The HttpRuntime.Cache also allows you to set various other characteristics, such as (optional) cache item priority and expiry time.




回答2:


with the cache you can easily set an enddate to the validity; the cache object expires the content automaticly.

also the cache can be given a priority, that less important items can be given a low priority so when the server gets high load, that item is removed first

with cahce however you allways have to do some extra effort in your unit test because the httpcontext isn't available during unit tests.




回答3:


HttpRuntime.Cache allows you to specify expiration callback, but with static dictionary you will have to wait for a query to run your expiration loop of your cache items.



来源:https://stackoverflow.com/questions/6922763/httpruntime-cache-vs-static-dictionary-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!