Reputation: 2861
I'm trying to put a caching system in place as per a tutorial I followed. The concept seems easy to understand but when it comes to implement it, I'm getting the following error message :
'AsyncLazy' does not contain a definition for 'GetAwaiter' and the best extension method overload 'AwaitExtensions.GetAwaiter(TaskScheduler)' requires a receiver of type 'TaskScheduler'
Here below is my code :
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;
}
}
}
I don't really get what's wrong since I declared my method as async so any lead would be appreciated.
Upvotes: 0
Views: 318
Reputation: 143453
It seems that you need to invoke GetValueAsync
on your asyncLazyValue
like this var result = await asyncLazyValue.GetValueAsync();
Upvotes: 1