【发布时间】:2020-11-06 10:45:35
【问题描述】:
您好,我正在尝试创建一个接收请求的缓存方法和一个函数,以防以前没有为请求缓存任何内容,它将执行作为参数传递的委托函数。 我一直在看 Delegates 和 Funcs 的视频,但材料总是非常基础,并且 delegate 的返回类型是强类型。我需要一些通用的东西来用于不同的 dtos(对象被缓存)。
我有一些自定义属性来装饰我想要缓存的 ClasseDTO,但这工作正常,所以请忽略。
public async Task<AdministrationDashboardDto> GetAdministrationKPIsAsync()
{
AdministrationDashboardDto dto = new AdministrationDashboardDto();
var x = await TryGetInCacheAsync(dto, () => _iKpisService.GetAdministrationKPIsAsync());
return (AdministrationDashboardDto)x;
}
private async Task<object> TryGetInCacheAsync<T>(object request, Func<T> p)
{
var cacheQuery = request.GetType().GetCustomAttribute<CacheObjectAttribute>();
if (cacheQuery != null)
{
var cacheKey = string.IsNullOrEmpty(cacheQuery.CacheKey)
? CacheHelper.GenerateCacheKeyFromRequest(dto)
: cacheQuery.CacheKey;
var cachedResponse = await _cacheService.GetCacheValueAsync(cacheKey);
if (cachedResponse != null)
{
//_logger.LogInformation($"Request {typeof(TRequest).Name} served from cache");
return cachedResponse;
}
var actualResponse = await Task.FromResult(p);
await _cacheService.SetCacheValueAsync(cacheKey, actualResponse, cacheQuery.TimeSpanForCacheInvalidation);
return actualResponse;
}
return null;
}
【问题讨论】:
-
你是在
var actualResponse = p()之后吗?您正在创建一个Task<Func<T>>,其中Task已经完成,这似乎毫无意义。 -
您的目标是在缓存中存储一个函数?为什么?有什么意义?
-
@CaiusJard nops,如果该请求的缓存中没有任何内容,则将执行委托函数。然后该函数将执行从源获取数据并将其添加到缓存中以供下次使用。
标签: c# asynchronous delegates