[英]Multiple calls to async function with cache in C#
我有一個可以同時從許多UI元素調用的函數:
在Psudeo代碼中
public async Task<Customer> GetCustomer(){
if(IsInCache)
return FromCache;
cache = await GetFromWebService();
return cache;
}
如果10個UI元素同時全部調用,我如何確保只調用一次GetFromWebService (),這是非常昂貴的。
使用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;
}
這將確保只創建一個 Task
,並且在至少發出一個請求之前不會進行Web服務調用。 然后,任何將來的請求將返回可以等待獲取值的相同Task
(無論是正在進行還是完成)。
如果緩存是內存中的,則可以緩存任務而不是結果:
private Task<Customer> _cache;
public Task<Customer> GetCustomerAsync()
{
if (_cache != null)
return _cache;
_cache = GetFromWebServiceAsync();
return _cache;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.