CSharp · Console
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
private static ConcurrentDictionary<string, Lazy<Task<DateTime>>> _cache = new();
public static async Task Main()
{
Console.WriteLine("Hello World");
await DoWork();
Console.WriteLine("----------------------------------------");
// Now wait 2 seconds.
await Task.Delay(2000);
// Lets run this all again .. and see if we get a different result? we should get the same cached value.
await DoWork();
}
public static async Task DoWork()
{
List<Task<DateTime>> tasks = new();
// Just so we can compare this time to the results times.
var start = DateTime.UtcNow;
Console.WriteLine("The Start: " + start + " / " + start.Ticks);
// Setup all the tasks (which are not ran/executed yet).
for(var i = 0; i < 10; i++)
{
tasks.Add(GetDateFromCache());
}
// Await for all the tasks to run and complete.
await Task.WhenAll(tasks);
// Display all the results from the tasks.
foreach(var task in tasks)
{
Console.WriteLine(task.Result + " / " + task.Result.Ticks);
}
var end = DateTime.UtcNow;
Console.WriteLine("The End: " + end + " / " + end.Ticks);
}
public static async Task<DateTime> GetDateFromCache()
{
var result = await _cache.GetOrAdd("someDateTime", new Lazy<Task<DateTime>>(async () =>
{
var someData = await GetDataFromSomeExternalDependency();
return DateTime.UtcNow;
})).Value;
return result;
}
public static async Task<int> GetDataFromSomeExternalDependency()
{
await Task.Delay(2000);
return 1;
}
}