Caching in C#/.Net

Caching in C#/.Net

If you're using ASP.NET, you could use the Cache class (System.Web.Caching).

Here is a good helper class: c-cache-helper-class

If you mean caching in a windows form app, it depends on what you're trying to do, and where you're trying to cache the data.

We've implemented a cache behind a Webservice for certain methods

(using the System.Web.Caching object.).

However, you might also want to look at the Caching Application Block. (See here) that is part of the Enterprise Library for .NET Framework 2.0.

.NET 4 Caching Support

I assume you are getting at this, System.Runtime.Caching, similar to the System.Web.Caching and in a more general namespace.

See http://deanhume.com/Home/BlogPost/object-caching----net-4/37

and on the stack,

is-there-some-sort-of-cachedependency-in-system-runtime-caching and,

performance-of-system-runtime-caching.

Could be useful.

Data Caching in ASP.Net

I always add the following class to all my projects which give me easy access to the Cache object. Implementing this, following Hasan Khan's answer would be a good way to go.

public static class CacheHelper
{
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="o">Item to be cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T o, string key, double Timeout)
{
HttpContext.Current.Cache.Insert(
key,
o,
null,
DateTime.Now.AddMinutes(Timeout),
System.Web.Caching.Cache.NoSlidingExpiration);
}

/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
HttpContext.Current.Cache.Remove(key);
}

/// <summary>
/// Check for item in cache
/// </summary>
/// <param name="key">Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
return HttpContext.Current.Cache[key] != null;
}

/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <param name="value">Cached value. Default(T) if item doesn't exist.</param>
/// <returns>Cached item as type</returns>
public static bool Get<T>(string key, out T value)
{
try
{
if (!Exists(key))
{
value = default(T);
return false;
}

value = (T)HttpContext.Current.Cache[key];
}
catch
{
value = default(T);
return false;
}

return true;
}
}

How to use effective caching in .NET?

I'm still not quite sure what you're asking. My best guess is it sounds like you're trying to let a cache know when its data is stale.

Most caching implementations have this built in. Basically, you can expire a cache item (usually be removing it from the cache) when it has been updated.

For example, if you're just using the plain old built in caching that comes with ASP.net:

private static Cache Cache;

public void AddItem(string data)
{
//Do a database call to add the data

//This will force clients to requery the source when GetItems is called again.
Cache.Remove("test");
}

public List<string> GetItems()
{
//Attempt to get the data from cache
List<string> data = Cache.Get("test") as string;

//Check to see if we got it from cache
if (data == null)
{
//We didn't get it from cache, so load it from
// wherever it comes from.
data = "From database or something";

//Put it in cache for the next user
Cache["test"] = data;
}

return data;
}

UPDATE I updated the code sample to return a list of strings instead of just a string. This should make it more obvious what is happening.

To reiterate, the GetItems() call retrieves a list of strings. If that list is in cache, the cached list is returned. Otherwise, the list is retrieved and cached / returned.

The AddItem method explicitly removes the list from the cache, forcing the requery of the data source.

Is there anyway to cache function/method in C#

You can create caching attributes with PostSharp. You can use the Cache attribute.

Looking for a very simple Cache example

.NET provides a few Cache classes

  • System.Web.Caching.Cache - default caching mechanizm in ASP.NET. You can get instance of this class via property Controller.HttpContext.Cache also you can get it via singleton HttpContext.Current.Cache. This class is not expected to be created explicitly because under the hood it uses another caching engine that is assigned internally.
    To make your code work the simplest way is to do the following:

    public class AccountController : System.Web.Mvc.Controller{ 
    public System.Web.Mvc.ActionResult Index(){
    List<object> list = new List<Object>();

    HttpContext.Cache["ObjectList"] = list; // add
    list = (List<object>)HttpContext.Cache["ObjectList"]; // retrieve
    HttpContext.Cache.Remove("ObjectList"); // remove
    return new System.Web.Mvc.EmptyResult();
    }
    }
  • System.Runtime.Caching.MemoryCache - this class can be constructed in user code. It has the different interface and more features like update\remove callbacks, regions, monitors etc. To use it you need to import library System.Runtime.Caching. It can be also used in ASP.net application, but you will have to manage its lifetime by yourself.

    var cache = new System.Runtime.Caching.MemoryCache("MyTestCache");
    cache["ObjectList"] = list; // add
    list = (List<object>)cache["ObjectList"]; // retrieve
    cache.Remove("ObjectList"); // remove

Caching in .Net Windows application

"As It is a windows based application and I didn't found any support for caching in Windows application"

This is False.

You can get caching class in Framework 4.0. It can be either windows based applications or web-based. Here are the docs.

Example:

 using System.Runtime.Caching;

private static MemoryCache cache = MemoryCache.Default;


Related Topics



Leave a reply



Submit