与异步延迟加载特性 [英] Lazy load properties with Async
问题描述
我已经学会了在我的仓库延迟加载特性。现在,我想这样做,但我还需要从网页加载的东西(使用HttpClient的),这意味着我的财产将是异步。
I've learned to lazy load properties in my repository. Now I'd like to do that, but I also need to load something from a web page (using Httpclient) which means my property will be async.
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是告诉我,
However, visual studio is telling me that
的修饰符异步不适用于这个项目的
,而在第一行突出的单词新闻。
while highlighting the word "News" in the first line.
是否有可能做到这一点?还是我写一个单独的方法?
Is it possible to do this? Or do I have to write a separate method?
推荐答案
首先,有副作用的特性通常不是所有的好。
First of all, properties with side-effects are usually not all that good.
在此情况下,只需阅读的这个属性会揭开序幕一个线程,一些网络流量,并在远程服务器上进行一些处理。
In this case, simply reading this property would kick off a thread, some network traffic, and some processing on a remote server.
这应该是一个方法,而不是一个属性。
This should be a method, not a property.
其次,编译器是正确的,属性不准是异步的。现在,你可以肯定的写的返回一个异步任务,但你不能使用异步
关键字属性。基本上只是拿走从财产申报的异步
关键字。
Secondly, the compiler is right, properties are not allowed to be asynchronous. Now, you can definitely write a property that returns an asynchronous task, but you're not allowed to use the async
keyword. Basically just take away the async
keyword from the property declaration.
但事实上,异步
不是对性能的法律是,你应该写一个方法,而不是一个属性另一条线索。
But the fact that async
is not legal on properties is another clue that you should write a method, not a property.
<击> 注意的异步
关键字实际上不是在$ C $所需的C你张贴的,因为你不实际使用中存在的等待
关键字。因此,你可以简单地删除异步
关键字完全,因为它不是必需的。事实上,如果你要在这个改变的方法,编译器会因为你没有使用的await
告诉你,这是不必要的。击> (删除OP编辑的问题后。)的
Note The (Removed after OP edited the question.)async
keyword is not actually required in the code you've posted, since you're not actually using the await
keyword in there. As such, you can simply remove the async
keyword altogether, since it is not required. In fact, if you were to change this over to a method, the compiler will tell you that it is unnecessary since you're not using await
.
这篇关于与异步延迟加载特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!