I'm trying to synchronise a webapi that's going to serve images. When I request a specific image, it will check whether the image already exists and return it if it does, or if it doesn't exist it will create it and then return it.
My problem is that it's obviously not thread safe just like that; I have one thread come in and determine the image doesn't exist and starting to create it, while another request comes in and also determines the image doesn't exist (just yet) and tries to create it as well. I know I could lock the whole thing to avoid the issue, but I'm trying to avoid that. There will be 100,000s of images, and I don't see why I need to stop all threads from reading the other images just because one image doesn't exist yet. Is there a "usual" way of doing this? Images are requested by ids, can I lock on the id of a particular image? For example
List<long> _locks = new List<long>();
_locks.Add(17);
lock(_locks[0]){...}
It just doesn't look right... surely there's a better solution?