How to cached in C # .NET an information for multiple users?

-2

I have a list of objects, and I would like every user who accessed a page to add their objects to the cache. And that this cache was worth to the next person who accessed the same url.

Example, I have the url "/ objects / id-6", the first user that access it will write the cache, and so all the next users that access this url, will not need to consult the database because they will pull the data of the cache.

    
asked by anonymous 30.11.2017 / 21:22

1 answer

1

Peter, you have a few options. Memory cache or distributed cache, for example Redis.

In memorycache you can store the key / value, as the example:

 protected MemoryCache cache = new MemoryCache("CachingProvider");

    static readonly object padlock = new object();

    protected virtual void AddItem(string key, object value)
    {
        lock (padlock)
        {
            cache.Add(key, value, DateTimeOffset.MaxValue);
        }
    }

    protected virtual void RemoveItem(string key)
    {
        lock (padlock)
        {
            cache.Remove(key);
        }
    }

    protected virtual object GetItem(string key, bool remove)
    {
        lock (padlock)
        {
            var res = cache[key];

            if (res != null)
            {
                if (remove == true)
                    cache.Remove(key);
            }
            else
            {
                WriteToLog("CachingProvider-GetItem: Don't contains key: " + key);
            }

            return res;
        }
    }

It would be nice of you to create a cache layer in your application, when the database was changed or something like that would invalidate your cache and you would update it again.

I think that for your application MemoryCache already meets you, you have more information about where I got this code:

link

    
03.12.2017 / 13:12