Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

In Psudeo code

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.

like image 576
Ian Vink Avatar asked Sep 17 '25 12:09

Ian Vink


1 Answers

Use 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. Any future requests will then return the same Task (whether its in progress or complete) which can be awaited to get the value.

like image 182
Servy Avatar answered Sep 20 '25 03:09

Servy