asp.net-mvc - 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.
解决方案
您的方法接受Task<Func<T>>
which 不是方法,因此您不能像方法一样调用它,这正是编译器告诉您的。如果要将异步方法作为参数传递,则需要将类型更改为Func<Task<T>>
函数签名,该函数返回Task
然后可以等待。
推荐阅读
- html - Bootstrap Vue 导航栏无法填满屏幕
- mapi - 使用 Outlook Redemption 的全局地址列表
- node.js - 将图片上传到 S3 时访问被拒绝
- node.js - 如何在 NodeJS 中使用 fluent-ffmpeg 将图像转换为视频
- r - 将四个数据框列折叠成两个交错列
- sql - 在 Sql 中,如何根据范围计算值?
- c# - 我应该先存储需要转换为变量的数据吗?或多次调用字典索引器?
- android - 真实设备不显示地图,但模拟器显示正确。如何解决这个问题呢?
- java - HSSF setborderbottom 在最后一个 excel 单元格中不起作用
- swift - 属性不会在 swift5 中覆盖其超类中的任何属性