【发布时间】:2020-05-05 15:36:42
【问题描述】:
我正在尝试按照我遵循的教程安装一个缓存系统。这个概念似乎很容易理解,但在实现它时,我收到以下错误消息:
“AsyncLazy”不包含“GetAwaiter”的定义,最佳扩展方法重载“AwaitExtensions.GetAwaiter(TaskScheduler)”需要“TaskScheduler”类型的接收器
下面是我的代码:
using System;
using System.Linq;
using System.Runtime.Caching;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Threading;
public class TaskCache : ITaskCache
{
private MemoryCache _cache { get; } = MemoryCache.Default;
private CacheItemPolicy _defaultPolicy { get; } = new CacheItemPolicy();
public async Task<T> AddOrGetExisting<T>(string key, Func<Task<T>> valueFactory)
{
var asyncLazyValue = new AsyncLazy<T>(valueFactory);
var existingValue = (AsyncLazy<T>)_cache.AddOrGetExisting(key, asyncLazyValue, _defaultPolicy);
if (existingValue != null)
{
asyncLazyValue = existingValue;
}
try
{
var result = await asyncLazyValue; // ERROR HERE
// The awaited Task has completed. Check that the task still is the same version
// that the cache returns (i.e. the awaited task has not been invalidated during the await).
if (asyncLazyValue != _cache.AddOrGetExisting(key, new AsyncLazy<T>(valueFactory), _defaultPolicy))
{
// The awaited value is no more the most recent one.
// Get the most recent value with a recursive call.
return await AddOrGetExisting(key, valueFactory);
}
return result;
}
catch (Exception)
{
// Task object for the given key failed with exception. Remove the task from the cache.
_cache.Remove(key);
// Re throw the exception to be handled by the caller.
throw;
}
}
}
由于我将我的方法声明为异步,因此我并没有真正理解问题所在。
【问题讨论】:
-
可以添加usings吗?
-
@GuruStron 确定,答案已更新。