Assume the following code
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
Lazy<TimeSpan> lm = new Lazy<TimeSpan>(GetDataAsync1, System.Threading.LazyThreadSafetyMode.PublicationOnly);
return new string[] { "value1", "value2", lm.Value.ToString() };
}
private TimeSpan GetDataAsync1()
{
return GetTS().ConfigureAwait(false).GetAwaiter().GetResult();
}
// I Cant change this method, and what is inside it...
private async Task<TimeSpan> GetTS()
{
var sw = Stopwatch.StartNew();
using (var client = new HttpClient())
{
var result = await client.GetAsync("https://www.google.com/");
}
sw.Stop();
return sw.Elapsed;
}
}
The point is that I am getting some data from remote server, and want to cache that for later use. As remote server may fail in a given point, I dont want to cache exception, but only success result... So keeping than awaiting the value will not work for me
// Cant use this, because this caches failed exception as well
Lazy<Task...> lz = ...
await lz.Value
But above snipped, as expected produce a deadlock, given that I cant change GetTS, is it possible to force Lazy work with my logic?