gpt4 book ai didi

c# - 为什么这个异步 lambda 函数调用不能在 C# 中编译?

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:01 25 4
gpt4 key购买 nike

在我的理解中,我似乎遗漏了一些非常基本的东西。我正在尝试调用一个需要 Func<T> 的异步函数由调用者传入,以防异步函数在缓存中找不到值。我真的很困惑为什么我的代码不能编译。

我的调用代码如下

static void Main(string[] args)
{
Func<Task<string>> dataFetcher = async () =>
{
string myCacheValue = await new HttpClient().GetStringAsync("http://stackoverflow.com/");
return myCacheValue;
};

MyCache<string> cache = new MyCache<string>();

string mValue = cache.GetOrCreateAsync("myCacheKey", dataFetcher).Result;

}

MyCache如下

internal class MyCache<T> where T: class
{
private Cache localCache = null;

public MyCache()
{
localCache = new Cache();
}
public T GetOrCreate(string cacheKey, Func<T> doWork)
{
T cachedObject = null;
if (string.IsNullOrEmpty(cacheKey) || string.IsNullOrWhiteSpace(cacheKey))
return cachedObject;

cachedObject = localCache.Get(cacheKey) as T;

if (null == cachedObject)
{
cachedObject = doWork();
}

localCache.Add(cacheKey, cachedObject, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

return cachedObject;
}

public async Task<T> GetOrCreateAsync(string cacheKey, Func<T> doWork)
{
T cachedObject = null;

if (string.IsNullOrEmpty(cacheKey) || string.IsNullOrWhiteSpace(cacheKey))
return cachedObject;

try
{
cachedObject = await Task.Factory.StartNew<T>(doWork);
localCache.Add(cacheKey, cachedObject, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
catch (Exception)
{
cachedObject = null;
}
finally
{
}

return cachedObject;
}
}

在调用代码行

string mValue = cache.GetOrCreateAsync("myCacheKey", dataFetcher).Result;

给我一​​个编译时错误 Argument 2: cannot convert from System.Func<System.Threading.Tasks.Task<string>> to System.Func<string>

我不知道我错过了什么?如果有人可以提供帮助,那就太好了!

谢谢~KD

最佳答案

使用重载方法并传递 Func<Task<T>>论证它。然后您可以等待该结果(即 Task<T> )。

public async Task<T> GetOrCreateAsync(string cacheKey, Func<Task<T>> doWorkAsync)
{
T cachedObject = null;

if (string.IsNullOrEmpty(cacheKey) || string.IsNullOrWhiteSpace(cacheKey))
return cachedObject;

try
{
cachedObject = await doWorkAsync();
localCache.Add(cacheKey, cachedObject, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
catch (Exception)
{
cachedObject = null;
}
finally
{
}

return cachedObject;
}

关于c# - 为什么这个异步 lambda 函数调用不能在 C# 中编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40558237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com