How to create memory cache with async generator

Andrus 121 Reputation points
2021-09-26T09:57:23.043+00:00

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.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-09-27T02:38:50.23+00:00

    Hi @AndRus ,

    CS0149: Method name expected

    To solve this issue, you can try to change the parameter type from Task<Func<T>> to Func<Task<T>>.

    After modified, the result as below:

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

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.