Home > OS >  How to create memory cache with async generator
How to create memory cache with async generator

Time:09-29

I tried to create cache with async getter method which reads data from databae using EF Core in ASP.NET 5 Core MVC application:

using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;

    public sealed class CacheManager
    {
        readonly IMemoryCache memoryCache;
        public CacheManager(IMemoryCache memoryCache)
        { 
            this.memoryCache = memoryCache;
        }
    
        public async Task<T> GetAsync<T>(string key, Task<Func<T>> generatorasync)
        {
            var cacheEntry = await
                  memoryCache.GetOrCreateAsync<T>(key, async entry =>
                  {
                      entry.SlidingExpiration = TimeSpan.FromSeconds(15 * 60);
                      return await generatorasync();
                  });
            return cacheEntry;
        }
    }

Line

              return await generatorasync();

throws syntax error

CS0149: Method name expected

Hoe to fix it ? Which is best practice to create such cache ?

Andrus.

CodePudding user response:

Your method accepts the Task<Func<T>> which is not a method so you cannot call it like a method and this is exactly what compiler is telling you. If you want to pass the async method as the parameter you need to change the type to Func<Task<T>> which is the signature of a function which returns the Task which then can be awaited.

  • Related