【问题标题】:How to create memory cache with async generator如何使用异步生成器创建内存缓存
【发布时间】:2021-11-18 20:12:50
【问题描述】:

我尝试使用异步 getter 方法创建缓存,该方法在 ASP.NET 5 Core MVC 应用程序中使用 EF Core 从数据库读取数据:

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;
        }
    }

线

              return await generatorasync();

抛出语法错误

CS0149:需要方法名称

锄头来修复它?创建此类缓存的最佳做法是什么?

安德鲁斯。

【问题讨论】:

标签: asp.net-mvc asp.net-core .net-core asp.net-core-mvc memorycache


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-05-12
    • 2013-10-30
    • 1970-01-01
    • 2020-06-22
    • 2016-03-11
    • 1970-01-01
    • 2017-09-08
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多