Let's say I have a scoped service called IPackageLoader
with one simple method GetAsync(string packageName)
that enables us to retrieve a package based on one HTTP GET call.
Since it is a HTTP GET call, it is idempotent, so there's no point in making multiple requests if GetAsync(string packageName)
gets called multiple times.
Example:
packageLoader.GetAsync("dotnet/aspnetcore")
packageLoader.GetAsync("dotnet/aspnetcore")
packageLoader.GetAsync("dotnet/efcore")
If there isn't some lock mechanism here, the second request will be made while it could just wait for the first one, save it and return it. However, the third request, since it is to get some other package, could be made without awaiting.
I tried to use SemaphoreSlim but I failed, since I locked on the first request, and the second one would wait for the first one to arrive as desired. However, if I tried to get a different package, using SemaphoreSlim I'll need to wait unnecessarily.
Any ideas on how to achieve this behavior? Maybe some class from the library that allows me to lock based on some key - instead just locking while any request is being done?