Search code examples
asp.netmultithreadinglockingblocking

How to organize ASP.NET request locking or row locking in DB


I've asp.net page/handler to access images. When performed fist request to the image I resize image to standard size(save on disk) and return it. So I need lock all request to the image except one. This one will resize image. Image identified by ID in URL, so I guess one lock object required per one image(ID in URL). My question is How can I organize this lock model?

My idea add lock object in Application (Application is synchronized) like this Application.Add(Request[Id], new object()); and use it to locking competitive threads.

This task like row locking of DB or locking element in collection.

Thanks for your replay.


Solution

  • The easiest way is locking image file with.

    
    using (FileStream fs = new FileStream("image.file", FileMode.Create, FileAccess.Write, FileShare.None))
    {
    
    resize image here 
    
    }
    
    

    When second(third etc) thread try to create file the Exception "The process cannot access the file ..." will throw. And I process this exception in code.