简体   繁体   English

在C#中使用缓存多次调用异步函数

[英]Multiple calls to async function with cache in C#

I have a function that can be called from many UI elements at the same time: 我有一个可以同时从许多UI元素调用的函数:

In Psudeo code 在Psudeo代码中

public async Task<Customer> GetCustomer(){
   if(IsInCache)
      return FromCache;

   cache = await GetFromWebService();
   return cache;

}

If 10 UI element all call at the same time, how do I make sure GetFromWebService () is called just once, it is very expensive. 如果10个UI元素同时全部调用,我如何确保调用一次GetFromWebService (),这是非常昂贵的。

Use Lazy . 使用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;
}

This will ensure that exactly one Task is ever created, and that the web service call isn't made until at least one request is made. 这将确保只创建一个 Task ,并且在至少发出一个请求之前不会进行Web服务调用。 Any future requests will then return the same Task (whether its in progress or complete) which can be awaited to get the value. 然后,任何将来的请求将返回可以等待获取值的相同Task (无论是正在进行还是完成)。

If your cache is in-memory, you can cache the task rather than the result: 如果缓存是内存中的,则可以缓存任务而不是结果:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM