Radu D
Radu D

Reputation: 3555

Lock checking of existing file section

In my website I use a controller to generate thumbnail of images. my code looks like:

var filePath = getThumbnailPath(); 
if (!File.Exists(filePath) 
{
    ... create thumbnail  
}    
return new Filestream(...)

The problem is that if two users request the same thumbnail and if this is not created I will get exception when creating it. How can I efficiently use a lock on the file name object without introducing too much overhead?

Refactored code after Aristos's comment:

 Mutex m = new Mutex(false, originalImagePath);
 m.WaitOne();
 try
 {
     if (!File.Exists(originalImagePath))
     { 
          ... create thumbnail
     }
 }
 finally
 {
     m.ReleaseMutex();
 } 

Upvotes: 2

Views: 110

Answers (2)

Peter Ritchie
Peter Ritchie

Reputation: 35881

ASP.NET sites have a concept of being able to run more than one process (e.g. web farms, etc.). lock only locks within a single process. If, for whatever reason, your code ran in more than one process, you'd be back to the same problem.

Also, your use of the dictionary needs to be made thread-safe. The way it is, it could write more than one value for the same filename.

I'd recommend using a named Mutex. This allows mutual exclusion across processes. The name of the mutex can simply be the filename. No need for a dictionary.

Making a network request to another service seems like it it was introduce even more latency into requests to your site. (e.g. a request to your site for an image needs to make a secondary network request to this "Service" to get the image --or get the location of the image).

Upvotes: 1

oleksii
oleksii

Reputation: 35905

Delegate creation of the thumbnails to other service. User will produce a request to create a thumbnail. Another service will consume this request and do the actual work.

What is a service, you can choose for your own. It can be a WCF service, a Windows service, a message queue or something else.

It is not usually a good idea to use locking in ASP.NET website directly as it will introduce a bottleneck.

Upvotes: 3

Related Questions