Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MemoryCache in C# Core Console app?

I would like to use the Microsoft.Extensions.Caching.Memory.MemoryCache in a .NET Core 2.0 console app (Actually, in a library that is either used in a console or in a asp.net app)

I've created a test app:

using System;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());

            int count = cache.Count;
            cache.CreateEntry("item1").Value = 1;
            int count2 = cache.Count;
            cache.TryGetValue("item1", out object item1);
            int count3 = cache.Count;
            cache.TryGetValue("item2", out object item2);
            int count4 = cache.Count;

            Console.WriteLine("Hello World!");
        }
    }
}

Unfortunately, this is not working. The items are not added to the cache and they can not be retrieved.

I suspect I need to use DependencyInjection, doing something like this:

using System;
using Microsoft.Extensions.DependencyInjection;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var provider = new Microsoft.Extensions.DependencyInjection.ServiceCollection()
                .AddMemoryCache()
                .BuildServiceProvider();

            //And now?

            var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());

            var xxx = PSP.Helpers.DependencyInjection.ServiceProvider;
            int count = cache.Count;
            cache.CreateEntry("item1").Value = 1;
            int count2 = cache.Count;
            cache.TryGetValue("item1", out object item1);
            int count3 = cache.Count;
            cache.TryGetValue("item2", out object item2);
            int count4 = cache.Count;

            Console.WriteLine("Hello World!");
        }
    }
}

Unfortunately, this is also not working, I suspect I shouldn't create a new memory cache, but get it from the service provider, but haven't been able to do that.

Any ideas?

like image 270
remcolam Avatar asked Aug 18 '17 08:08

remcolam


People also ask

How does MemoryCache work?

Memory caching (often simply referred to as caching) is a technique in which computer applications temporarily store data in a computer's main memory (i.e., random access memory, or RAM) to enable fast retrievals of that data. The RAM that is used for the temporary storage is known as the cache.

What is MemoryCache?

Cache memory is a chip-based computer component that makes retrieving data from the computer's memory more efficient. It acts as a temporary storage area that the computer's processor can retrieve data from easily.

How do I check MemoryCache?

Right-click on the Start button and click on Task Manager. 2. On the Task Manager screen, click on the Performance tab > click on CPU in the left pane. In the right-pane, you will see L1, L2 and L3 Cache sizes listed under “Virtualization” section.

How do I initialize memory cache?

Refer to the following example to see how to initialize the cacheItemPolicy class and add a time value to store the data in the cache. var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset. Now. AddSeconds(120.0) }; var result = cache.


2 Answers

After configuring the provider retrieve the cache via the GetService extension method

var provider = new ServiceCollection()
                       .AddMemoryCache()
                       .BuildServiceProvider();

//And now?
var cache = provider.GetService<IMemoryCache>();

//...other code removed for brevity;

From comments:

It's not needed to use dependency injection, the only thing needed was disposing the return value of CreateEntry(). The entry returned by CreateEntry needs to be disposed. On dispose, it is added to the cache:

using (var entry = cache.CreateEntry("item2")) { 
    entry.Value = 2; 
    entry.AbsoluteExpiration = DateTime.UtcNow.AddDays(1); 
}
like image 189
Nkosi Avatar answered Sep 20 '22 20:09

Nkosi


IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
object result = cache.Set("Key", new object());
bool found = cache.TryGetValue("Key", out result);

See full Memory Cache Sample in GitHub.

You need to add NuGet Microsoft.Extensions.Caching.Memory packages in your project for use MemoryCache

like image 30
Stanislav Prusac Avatar answered Sep 19 '22 20:09

Stanislav Prusac