【问题标题】:Caching task results - AsyncLazy does not contain a definition for GetAwaiter缓存任务结果 - AsyncLazy 不包含 GetAwaiter 的定义
【发布时间】: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 确定,答案已更新。

标签: c# caching task


【解决方案1】:

您似乎需要在您的asyncLazyValue 上调用GetValueAsync,就像这样var result = await asyncLazyValue.GetValueAsync();

【讨论】:

  • 谢谢,确实是这样!
猜你喜欢
  • 1970-01-01
  • 2012-08-04
  • 2017-04-20
  • 2017-11-20
  • 2018-08-21
  • 2019-02-01
  • 2016-12-15
  • 2017-04-08
  • 1970-01-01
相关资源
最近更新 更多