I need to cache a generic list so I dont have to query the databse multiple times. In a web application I would just add it to the httpcontext.current.cache
. What is the proper way to cache objects in console applications?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There a many ways to implement caches, depending of what exactly you are doing. Usually you will be using a dictionary to hold cached values. Here is my simple implementation of a cache, which caches values only for a limited time:
You can pass a lambda expression to the Get method, which retrieves values from a db for instance.
In a class-level variable. Presumably, in the
main
method of your console app you instantiate at least one object of some sort. In this object's class, you declare a class-level variable (aList<String>
or whatever) in which you cache whatever needs caching.Use Singleton Pattern.
http://msdn.microsoft.com/en-us/library/ff650316.aspx
Ref: How do I cache a dataset to stop round trips to db?
Keep it as instance member of the containing class. In web app you can't do this since page class's object is recreated on every request.
However .NET 4.0 also has MemoryCache class for this purpose.
You might be able to just use a simple Dictionary. The thing that makes the Cache so special in the web environment is that it persists and is scoped in such a way that many users can access it. In a console app, you don't have those issues. If your needs are simple enough, the dictionary or similar structures can be used to quickly lookup values you pull out of a database.