【发布时间】:2021-04-28 01:29:45
【问题描述】:
我正在使用 c# .net core 5 Blazer WebService。
我有一项服务,其中包含事物列表作为属性。
public class Service : IService
{
public HashSet<Thing> Things {get; set;}
}
现在我想从磁盘加载事物,所以我将它们私下缓存在服务中
public class Service : IService
{
private HashSet<Thing> _things
public HashSet<Thing> Things => _things : LoadThings();
}
但是 LoadThings() 访问磁盘,所以我希望该 IO 异步运行并等待它。但是现在 LoadThings() 需要异步,我做不到:
public class Service : IService
{
private HashSet<Thing> _things
public HashSet<Thing> Things => _things : await LoadThings();
}
我明白为什么了;异步链丢失。
所以我的问题是:如果 _things 为空,那么获取 _things 但等待异步 IO 的最佳方法是什么?
【问题讨论】:
-
没有异步属性。将属性替换为返回缓存数据或检索新数据的方法
-
如果你想延迟初始化数据而不是实际缓存它们过期你可以检查AsyncLazy
-
But LoadThings() accesses the disk so I want that IO to run asynchronously取决于你在做什么(在LoadThings),记住这可能不是要走的路,仍然可以同步运行;只是一个想法。
标签: c# .net-core async-await