簡體   English   中英

緩存任務結果 - AsyncLazy 不包含 GetAwaiter 的定義

[英]Caching task results - AsyncLazy does not contain a definition for GetAwaiter

我正在嘗試按照我遵循的教程放置一個緩存系統。 這個概念似乎很容易理解,但是在實現它時,我收到以下錯誤消息:

“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;
            }
        }
     }

自從我將我的方法聲明為異步之后,我並沒有真正明白什么是錯誤的,因此任何線索都會受到贊賞。

似乎您需要像這樣在asyncLazyValue上調用GetValueAsync var result = await asyncLazyValue.GetValueAsync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM