We have a static List of Foo. I'm trying to make sure that, if a Foo doesn't exist, grab it from the db. This operation (the DB-Get) is expensive so I'm wondering how we can do this?
for example:
if (list.Any(x => x.Name == Leia))
{
//list of Foo's doesn't have any foo with the name 'Leia'
var foo = db.GetFoo("Leia");
foos.Add(foo);
}
Initially, i was thinking of using Double-checked locking but i'm a bit unsure if that's the correct path I should be taking .. especially after reading a bit about it and the suggestion of using Lazy<T> instead .. except my instance isn't the issue here .. it's the ITEMS in the instance that i'm worried about.
NOTE: The key here is not so much about a thread-safe collection (ie. like a ConcurrentBag / ConcurrentDictionary, etc) .. but more about reducing the calls to the DB.
Scenario:
- 10 people hit the website at the same time
- all 10 people see that the item is missing from the collection.
- only 1x
db.GetFoo("Leia");is called - 9 others then retrieve the item from the collection (no db calls).
DISCLAIMER: I'm not sure if the title is correct - happy to hear suggestions on ammending it.