davidfowl / AspNetCoreDiagnosticScenarios

This repository has examples of broken patterns in ASP.NET Core applications
7.69k stars 740 forks source link

Recommended handling in ConcurrencyDictionary<string, Task<T>> when task fails #62

Open passuied opened 4 years ago

passuied commented 4 years ago

Hi @davidfowl,

Trying to get rid of Task.Result in our code and follow your approach in AsyncGuidance.md#concurrentdictionarygetoradd by storing the Task instead of the actual value. In our tests, it causes issue when the task fails (e.g. HTTP Exception) but the task obviously still gets added to the cache...

Any recommendations here?

Thanks, Patrick

davidfowl commented 3 years ago

@passuied Just saw this. This is a tricky one. If you want to remove the entry from the dictionary when it fails then you might need something like GetOrAddAsync (https://gist.github.com/davidfowl/3dac8f7b3d141ae87abf770d5781feed#file-concurrentdictionaryextensions-cs-L53).

bartelink commented 3 years ago

Another approach might be to wrap it like this: https://stackoverflow.com/a/33942013/11635 There's an evolution of that with expiration semantics too (there are some tests if one wanted to port it to C#)