首页 > 解决方案 > 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.

标签: asp.net-mvcasp.net-core.net-coreasp.net-core-mvcmemorycache

解决方案


您的方法接受Task<Func<T>>which 不是方法,因此您不能像方法一样调用它,这正是编译器告诉您的。如果要将异步方法作为参数传递,则需要将类型更改为Func<Task<T>>函数签名,该函数返回Task然后可以等待。


推荐阅读