c# - MemoryCache OutOfMemoryException -
i trying figure out how memorycache should used in order avoid getting out of memory exceptions. come asp.net background cache manages it's own memory usage expect memorycache same. not appear case illustrated in bellow test program made:
class program { static void main(string[] args) { var cache = new memorycache("cache"); (int = 0; < 100000; i++) { addtocache(cache, i); } console.readline(); } private static void addtocache(memorycache cache, int i) { var key = "file:" + i; var contents = system.io.file.readallbytes("file.txt"); var policy = new cacheitempolicy { slidingexpiration = timespan.fromhours(12) }; policy.changemonitors.add( new hostfilechangemonitor( new[] { path.getfullpath("file.txt") } .tolist())); cache.add(key, contents, policy); console.clear(); console.write(i); } }
the above throws out of memory exception after approximately reaching 2gb of memory usage (any cpu) or after consuming machine's physical memory (x64)(16gb).
if remove cache.add bit program throws no exception. if include call cache.trim(5) after every cache add see releases memory , keeps aproximately 150 objects in cache @ given time (from cache.getcount()).
is calling cache.trim program's responsibility? if when should called (like how can program know memory getting full)? how calculate percentage argument?
note: planning use memorycache in long running windows service critical have proper memory management.
Comments
Post a Comment