About the Caching Application Block

来源:互联网 发布:万能坐标转换软件 编辑:程序博客网 时间:2024/05/24 03:49

About the Caching Application Block

This topic has not yet been rated- Rate this topic
 

About the Caching Application Block

patterns & practices Developer Center

Enterprise Library

patterns & practices Developer Center

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Caching Application Block. An application block is reusable and extensible source code-based guidance that simplifies development of common caching functionality in .NET Framework applications.

Downloads
  • Latest Release: Enterprise Library 3.1 – May 2007 (for .NET Framework 2.0 and 3.0)
  • Enterprise Library 3.0 – April 2007 (for .NET Framework 2.0 and 3.0)
  • Earlier Release: Enterprise Library for .NET Framework 2.0, January 2006
  • Earlier Release: Enterprise Library for .NET Framework 1.1, June 2005
  • Patches and extensions for Enterprise Library can be downloaded from the Enterprise Library Community
License
  • End User Licensing Agreement (EULA)
Community
  • Enterprise Library Community

Contents

Introduction to the Caching Application Block
Design of the Caching Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Caching Application Block

The Enterprise Library Caching Application Block lets developers incorporate a local cache in their applications. It supports both an in-memory cache and, optionally, a backing store that can either be the database store or isolated storage. The application block can be used without modification; it provides all the needed functionality to retrieve, add, and remove cached data. Configurable expiration and scavenging policies are also part of the application block.

When building enterprise-scale distributed applications, architects and developers are faced with many challenges. Caching can help them to overcome some of these challenges, including the following:

  • Performance. Caching improves application performance by storing relevant data as close as possible to the data consumer. This avoids repetitive data creation, processing, and transportation.
  • Scalability. Storing information in a cache helps save resources and increases scalability as the demands on the application increase.
  • Availability. By storing data in a local cache, the application may be able to survive system failures such as network latency, Web service problems, and hardware failures.

Common Scenarios

The Caching Application Block is suitable if you encounter any of the following situations:

  • You must repeatedly access static data or data that rarely changes.
  • Data access is expensive in terms of creation, access, or transportation.
  • Data must always be available, even when the source, such as a server, is not available.

You can use the Caching Application Block with any of the following application types:

  • Windows Forms
  • Console application
  • Windows service
  • COM+ server
  • ASP.NET Web application or Web service if you need features not included in the ASP.NET cache

You should deploy the Caching Application Block within a single application domain. Each application domain can have one or multiple caches, either with or without backing stores. Caches cannot be shared among different application domains.

The Caching Application Block is optimized for performance and is both thread safe and exception safe. You can extend it to include your own expiration policies and your own backing store.

Example Application Code

The following code shows how to add an item to a cache and retrieve an item from the cache. It creates an object of typeProduct and then adds it to the cache, together with a scavenging priority of 2, an instruction not to refresh the item if it expires, and an expiration date of 5 minutes from the last time the item was accessed.

Note   The code does not include theProduct class definition.
[C#]CacheManager productsCache = CacheFactory.GetCacheManager(); string id = "ProductOneId"; string name = "ProductXYName"; int price = 50; Product product = new Product(id, name, price); productsCache.Add(product.ProductID, product, CacheItemPriority.Normal, null, new SlidingTime(TimeSpan.FromMinutes(5))); // Retrieve the item product = (Product) productsCache.GetData(id); [Visual Basic]Dim productsCache As CacheManager = CacheFactory.GetCacheManager() Dim id As String = "ProductOneId" Dim name As String = "ProductOneName" Dim price As Integer = 50 Dim newProduct As Product = New Product(id, name, price)productsCache.Add(newProduct.ProductID, newProduct, CacheItemPriority.Normal, Nothing, New SlidingTime(TimeSpan.FromMinutes(5))) ' Retrieve the item product = DirectCast(productsCache.GetData(id), Product) 

Design of the Caching Application Block

The Caching Application Block is designed to do the following:

  • It provides a set of APIs that are manageable in size.
  • It allows developers to incorporate the standard caching operations into their applications without having to learn the internal workings of the application block.
  • It uses the Enterprise Library Configuration Console for easy configuration.
  • It performs efficiently.
  • It is thread safe. Something is considered thread safe when it can be called from multiple programming threads without unwanted interaction among those threads.
  • It ensures that the backing store remains intact if an exception occurs while it is being accessed.
  • It ensures that the states of the in-memory cache and the backing store remain synchronized.

Design Highlights

Figure 1 shows the interrelationships between the key classes in the Caching Application Block.

Ff647011.entlib_cachingappblock(en-us,PandP.10).gif

Figure 1. Design of the Caching Application Block

When you initialize an instance of the CacheManager using theCacheFactory, it internally creates a CacheManagerFactory object, which in turn creates aCache object. After the Cache object is created, all data in the backing store is loaded into an in-memory representation that is contained in theCache object. Applications can then make requests to the CacheManager object to retrieve cached data, add data to the cache, and remove data from the cache.

When an application uses the GetData method to send a request to theCacheManager object to retrieve an item, the CacheManager object forwards the request to theCache object. If the item is in the cache, it is returned from the in-memory representation in the cache to the application. If it is not in the cache, the request returns the valueNULL. If the item is expired, the item also returns the value NULL.

When an application uses the Add method to send a request to theCacheManager object to add an item to the cache, the CacheManager object again forwards the request to theCache object. If there is already an item with the same key, theCache object first removes it before adding the new item to the in-memory store and the backing store. If the backing store is the default backing store,NullBackingStore, the data is written only to memory. If the number of cached items exceeds a predetermined limit when the item is added, theBackgroundScheduler object begins scavenging. When adding an item, the application can use an overload of theAdd method to specify an array of expiration policies, the scavenging priority, and an object that implements theICacheItemRefreshAction interface. This object can be used to refresh an expired item from the cache.

When adding an item that is not already in the in-memory hash table, the Cache object first creates a dummy cache item and adds it to the in-memory hash table. It then locks the cache item in the in-memory hash table, adds the item to backing store, and finally replaces the existing cache item in the in-memory hash table with the new cache item. (In the case where the item was already in the in-memory hash table, it replaces the dummy item.) If there is an exception while writing to the backing store, it removes the dummy item added to the in-memory hash table and does not continue. The Caching Application Block enforces a strong exception safety guarantee. This means that if anAdd operation fails, the state of the cache rolls back to what it was before it tries to add the item. In other words, either an operation is completed successfully or the state of the cache remains unchanged. (This is also true for theRemove and Flush methods.)

The BackgroundScheduler object periodically monitors the lifetime of items in the cache. When an item expires, theBackgroundScheduler object first removes it and then, optionally, notifies the application that the item was removed. At this point, it is the responsibility of the application to refresh the cache.

Getting Started

The Caching Application Block has been developed as a result of analyzing common enterprise development challenges and successful solutions to these challenges. However, because each application is unique, you will not find this application block suitable for every application. To evaluate this application block and determine its applicability to your projects, Microsoft suggests you dedicate at least half of a day to explore the application block. The following is a suggested evaluation approach:

  1. Download Enterprise Library.
  2. Install Enterprise Library and compile all application blocks and tools.
  3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
  4. Compile and run the QuickStart samples, and read through the related "QuickStart Walkthroughs" and "Key Scenarios" sections of the documentation.
  5. If the application block looks like a good fit for your application, try implementing a simple use case in your application or in a throw-away prototype application using the application block.

Community

Enterprise Library, like many patterns & practices deliverables, is associated with acommunity site. On this community site, you can post questions, provide feedback, or connect with other users for sharing ideas. Community members can also help Microsoft plan and test future deliverables, and download additional content, such as extensions and training material.

Feedback and Support

Questions? Comments? Suggestions? To provide feedback about this application block, or to get help with any problems, please visit theEnterprise Library Community site. The community site is the preferred feedback and support channel because it allows you to share your ideas, questions, and solutions with the entire community.

Enterprise Library is a guidance offering, designed to be reused, customized, and extended. It is not a Microsoft product. Code-based guidance is shipped "as is" and without warranties. Customers can obtain support through Microsoft Support Services for a fee, but the code is considered user-written by Microsoft support staff. For more information about our support policy, see theEnterprise Library home page.

Related Titles

  • Caching Architecture Guide for .NET Framework Applications
  • Application Architecture for .NET: Designing Applications and Services
  • Enterprise Library