10.18. Caching

ASP.NET 4.0 gives you the option to create and utilize custom cache providers. The cache provider can be set at an application, control, and even individual request level (by overriding the GetOutputCacheProviderName() method), offering very fine-grained control.

To create your own cache provider, you must inherit from System.Web.Caching.OutputCacheProvider.

10.18.1. Velocity

Before you create your own caching system (you crazy fool), you would be wise to take a look into Microsoft's new free distributed caching system, Velocity. Velocity provides a huge amount of functionality and is easily utilized by both web and Windows applications. Velocity presents a view of the cache that can be spread out among many machines and accessed by any type of application. For more information, please refer to http://msdn.microsoft.com/en-au/library/cc645013.aspx.

10.18.2. System.Runtime.Caching

In previous versions of .NET, caching functionality was contained in the System.Web assembly. To enable easier integration for nonweb clients, Microsoft has created the new System.Runtime.Caching assembly. System.Runtime.Caching contains abstract classes for creating your own cache provider and contains a new class called MemoryCache. MemoryCache can be used by nonweb clients; it offers a simple in-memory caching functionality. Microsoft says that the internal implementation of MemoryCache is similar to ASP.NET's cache.

The following example shows how to utilize MemoryCache to store a string for an hour (note you can also create watchers to invalidate the cache if an item changes and add them to the policy.ChangeMonitors property):

ObjectCache cache = MemoryCache.Default;
string testData = cache["someData"] as string;

if (testData == null)
{
    CacheItemPolicy policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(1));
    cache.Set("someData", "some test data", policy);
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.147