Skip to content

Instantly share code, notes, and snippets.

@nelsonprsousa
Created December 15, 2021 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonprsousa/46df0cf266c809485603fbf2ea57542e to your computer and use it in GitHub Desktop.
Save nelsonprsousa/46df0cf266c809485603fbf2ea57542e to your computer and use it in GitHub Desktop.
.NET 6
var dataLoader = new DataLoader();
Console.WriteLine("Executing...");
var t1 = dataLoader.LoadAsync("1");
var t2 = dataLoader.LoadAsync("1");
var t3 = dataLoader.LoadAsync("9999");
Console.WriteLine("Done Loading...");
Console.WriteLine(t1 == t2);
Console.WriteLine(t1 == t3);
Console.WriteLine(await t1);
Console.WriteLine(await t2);
Console.WriteLine(await t3);
public class DataLoader
{
private readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
private Dictionary<string, Task<string>> Data { get; set; }
public DataLoader()
{
this.Data = new Dictionary<string, Task<string>>();
}
public Task<string> LoadAsync(string id)
{
this.semaphoreSlim.Wait();
try
{
if (this.Data.TryGetValue(id, out var dataTask))
{
return dataTask;
}
dataTask = GetString(id);
this.Data.Add(id, dataTask);
return dataTask;
}
finally
{
this.semaphoreSlim.Release();
}
}
private async Task<string> GetString(string str)
{
await Task.Delay(5000);
return str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment