Ian*_*ink 3 c# asynchronous task-parallel-library async-await
我有一个可以同时从许多UI元素调用的函数:
在Psudeo代码中
public async Task<Customer> GetCustomer(){
if(IsInCache)
return FromCache;
cache = await GetFromWebService();
return cache;
}
Run Code Online (Sandbox Code Playgroud)
如果10个UI元素同时全部调用,我如何确保只调用一次GetFromWebService(),这是非常昂贵的.
Ser*_*rvy 12
使用Lazy.
//the lazy can be changed to an instance variable, if that's appropriate in context.
private static Lazy<Task<Customer>> lazy =
new Lazy<Task<Customer>>(() => GetFromWebService());
public Task<Customer> GetCustomer(){
return lazy.Value;
}
Run Code Online (Sandbox Code Playgroud)
这将确保始终创建一个 Task,并且在至少发出一个请求之前不会进行Web服务调用.然后,任何将来的请求将返回相同的Task(无论是正在进行还是完成),可以等待获得该值.
| 归档时间: |
|
| 查看次数: |
562 次 |
| 最近记录: |