gpt4 book ai didi

c# - 使用 Async 延迟加载属性

转载 作者:太空狗 更新时间:2023-10-29 22:06:34 29 4
gpt4 key购买 nike

我学会了在我的存储库中延迟加载属性。现在我想这样做,但我还需要从网页加载一些东西(使用 Httpclient),这意味着我的属性将是异步的。

public async Task<List<NewsModel>> News
{
get
{
if (_news == null)
{
CacheProvider cache = new CacheProvider();
object cachedNews = cache.Get("news");

if (cachedNews == null)
{
var client = new HttpClient();
// await HttpResponse
}

}
return _news;
}

set
{
_news = value;
}
}

但是,visual studio 告诉我

"The modifier async is not valid for this item"

同时突出显示第一行中的“新闻”一词。

这有可能吗?还是我必须编写一个单独的方法?

最佳答案

不支持异步属性。我描述了一个 number of workarounds在我的博客上。

在你的情况下,它听起来像 asynchronous lazy initialization将是一个很好的解决方案(也在我的博客中描述)。

关于c# - 使用 Async 延迟加载属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17975609/

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