2

We have some code which allows an image to be requested in different sizes and if it doesn't exist it creates it in that size and stores it. The problem we have is multiple requests when the image doesn't exist and it tries to create it for the first time.

While we are not currently on a web farm or distributed across multiple machines that is where we want to get to so what we need is a way to lock that section while only one thread/process creates the re-sized image and then allow any threads to continue returning the image.

What is the best way in ASP.NET C# to lock across multiple threads/machines (in a web farm scenario). I guess the only real choice is with some sort of DB table which we can store locks in perhaps on the image filename/id but then do the other threads have to keep calling the DB to see if the lock has been released?

If anyone has any experience of this type of scenario it would be appreciated. We are using ASP.NET MVC 4 with C# 4.5 and SQL Server 2008.

MarioDS
  • 12,895
  • 15
  • 65
  • 121
user351711
  • 3,171
  • 5
  • 39
  • 74
  • 1
    Depending on your system it might not be worth locking. You could always create the image if none already exists and then store the location of the new image. If it gets created 3 times and overwritten does it matter? If that created image is then accessed 50000 times thereafter the extra 2 generations might be worth the lack of pain from trying to lock... – Russell Troywest May 01 '13 at 09:56
  • See the answers http://stackoverflow.com/questions/7395692/what-is-the-best-way-to-create-a-lock-from-a-web-application?rq=1 – Scott Rickman May 10 '13 at 15:25

1 Answers1

0

Are you planning on have the same image generated on every server in the web farm? If that is OK then you can just use a Dictionary<FileName, Key> and have anyone wanting to create an image request a Key first then present this Key to the method that creates the image. This method will check the Key, generate the image if appropriate then delete the Key. Check the Dictionary for a Key for the specified FileName when a Key is requested, if one already exists reject the request, otherwise lock the Dictionary (it'll be need static), re-check for any existing Key, generate and insert a new Key into the Dictionary, return the Key. If you only want one instance of the image across the whole farm then you'll need a distributed cache service and some way of directing all requests for the image to the correct server - seems to defeat the point of farming / load balacing to me

Scott Rickman
  • 560
  • 5
  • 10