question

Andrus-0543 avatar image
0 Votes"
Andrus-0543 asked ZhiLv-MSFT answered

How to create memory cache with async generator

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.

dotnet-aspnet-core-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.