How to cache c# . NET information for multiple users?

Asked

Viewed 462 times

-2

I have a list of objects, and I would like each user who accesses 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 who accesses it will write the cache, and so all the next users who access this url, will not need to query the database because they will pull the cache data.

1 answer

1


Pedro, you have some options. Distributed memory cache or 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;
        }
    }

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

I believe that for your application Memorycache already serves you, has more information where I got this code:

https://www.codeproject.com/Articles/756423/How-to-Cache-Objects-Simply-using-System-Runtime-C

Browser other questions tagged

You are not signed in. Login or sign up in order to post.