Created
December 15, 2021 22:34
-
-
Save nelsonprsousa/46df0cf266c809485603fbf2ea57542e to your computer and use it in GitHub Desktop.
.NET 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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