Cache Operations
The first object to create when dealing with AppFabric caching is a DataCacheFactory. This can be created either with hard-coded configuration data that tells the factory how to contact the cache server, or with no configuration in which case it reads the configuration from your web.config/app.config file. My recommendation is that you keep your config information in your .config file, otherwise when you want to change something in your cache setup, you'll need to re-compile and re-distribute your application. The important thing to remember about the DataCacheFactory is it is expensive to create - you definitely don't want to create one of these for every cache operation. Consider using the Singleton pattern - see this question for more details.
// Create a factory reading the config info from the .config file
DataCacheFactory factory = new DataCacheFactory();
The main interface to a cache is through the Cache object. A Cache is obtained from the DataCacheFactory's GetCache method, passing in the name of the cache:
DataCache myCache = factory.GetCache("myCache");
Adding An Item to the Cache
Each item in a cache has a key, which is a string. The key must be unique to the cache - if you pass in a key that already exists you'll get an exception. The item to be cached must be serialisable so AppFabric can internally pass it around the servers in the cache. At the most basic level, items are added to the cache using the Add method.
object myCachedItem = new Object();
string myCachedItemKey = "MyCacheKey";
myCache.Add(myCachedItemKey, myCachedItem);
Removing an Item from the Cache
myCache.Remove(myCachedItemKey);
Simple as.<
Also worth adding that the Singleton pattern is pretty much essential if you're using the Azure AppFabric Caching service as each instatiation of a DataCacheFactory creates a new connection to the Azure AppFabric Caching service. Since the number of connections is limited based upon the size of your cache (128MB cache includes 5 connections) you'll very quickly lockout all your connections if you don't re-use the same factory!