在控制台应用程序中缓存
我需要缓存通用列表,这样我就不必多次查询数据库。在 Web 应用程序中,我只需将其添加到 httpcontext.current.cache
中。在控制台应用程序中缓存对象的正确方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
参考:如何缓存数据集停止到数据库的往返?
Ref: How do I cache a dataset to stop round trips to db?
您也许可以只使用简单的字典。缓存在 Web 环境中如此特殊的原因在于,它会持续存在,并且其作用范围可供许多用户访问。在控制台应用程序中,您不会遇到这些问题。如果您的需求足够简单,则可以使用字典或类似结构来快速查找从数据库中提取的值。
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.
实现缓存的方法有很多种,具体取决于您正在做什么。通常您将使用字典来保存缓存值。下面是我对缓存的简单实现,它仅在有限的时间内缓存值:
您可以将 lambda 表达式传递给 Get 方法,该方法例如从数据库检索值。
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.
使用单例模式。
http://msdn.microsoft.com/en-us/library/ff650316.aspx
Use Singleton Pattern.
http://msdn.microsoft.com/en-us/library/ff650316.aspx
将其保留为包含类的实例成员。在网络应用程序中,您无法执行此操作,因为页面类的对象会根据每个请求重新创建。
然而.NET 4.0也有MemoryCache类这个目的。
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.
在类级别变量中。据推测,在控制台应用程序的
main
方法中,您实例化了至少一个某种类型的对象。在此对象的类中,您声明一个类级变量(List
或其他),在其中缓存需要缓存的任何内容。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.这是我在控制台中使用的一个非常简单的缓存类,它具有自我清理功能并且易于实现。
用途:
类别:
Here is a very simple cache class I use in consoles that has self clean up and easy implementation.
The Usage:
The Class: