skip to Main Content

In Java Spring Boot, I can easily enable caching using the annotation @EnableCaching and make methods cache the result using @Cacheable, this way, any input to my method with the exact same parameters will NOT call the method, but return immediately using the cached result.

Is there something similar in C#?

What I did in the past was i had to implement my own caching class, my own data structures, its a big hassle. I just want an easy way for the program to cache the result and return the exact result if the input parameters are the same.

EDIT: I dont want to use any third party stuff, so no MemCached, no Redis, no RabbitMQ, etc… Just looking for a very simple and elegant solution like Java’s @Cacheable.

2

Answers


  1. Caches

    A cache is the most valuable feature that Microsoft provides. It is a type of memory that is relatively small but can be accessed very quickly. It essentially stores information that is likely to be used again. For example, web browsers typically use a cache to make web pages load faster by storing a copy of the webpage files locally, such as on your local computer.

    Caching

    Caching is the process of storing data into cache. Caching with the C# language is very easy. System.Runtime.Caching.dll provides the feature for working with caching in C#. In this illustration I am using the following classes:

    ObjectCache

    MomoryCache

    CacheItemPolicy

    1. ObjectCache

    : The CacheItem class provides a logical representation of a cache entry, that can include regions using the RegionName property. It exists in the System.Runtime.Caching.

    1. MomoryCache

    : This class also comes under System.Runtime.Caching and it represents the type that implements an in-cache memory.

    1. CacheItemPolicy

    : Represents a set of eviction and expiration details for a specific cache entry.

    .NET provides

    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 DataController : 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 updateremove 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
    
    Login or Signup to reply.
  2. You can write a decorator with a get-or-create functionality. First, try to get value from cache, if it doesn’t exist, calculate it and store in cache:

    public static class CacheExtensions
    {
        public static async Task<T> GetOrSetValueAsync<T>(this ICacheClient cache, string key, Func<Task<T>> function)
            where T : class
        {
            // try to get value from cache
            var result = await cache.JsonGet<T>(key);
            if (result != null)
            {
                return result;
            }
            // cache miss, run function and store result in cache
            result = await function();
            await cache.JsonSet(key, result);
            return result;
        }
    }
    

    ICacheClient is the interface you’re extending. Now you can use:

    await _cacheClient.GetOrSetValueAsync(key, () => Task.FromResult(value));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search