问题
I am facing a problem with Image caching by using files in ASP.NET. My detailed solution is:
For 1st request: I check the image file not exists and write the image file into hard disk. After that returns the url of the file to the browser
For later requests: the function just returns the url of the file to the browser
My problem is: sometimes with 1st requests, the browser can not get the image data from the url and cause the 404 - File Not Found error. I think it might because of the file is written but not ready for retrieving from browsers, but in the code I am using both "using statement" and "Dispose method" for bitmap & graphic objects to ensure everything are ready for accessing from browsers.
In more details, I am using the similar solution as in NopCommerce:
lock (s_lock) { ...........
using (var stream = new MemoryStream(LoadPictureBinary(picture))) {
using(var b = new Bitmap(stream)){
using(var newBitMap = new Bitmap(newSize.Width, newSize.Height)){
.......................
newBitMap.Save(
Path.Combine(this.LocalThumbImagePath, localFilename), ici, ep);
}
}
}
} // end lock
return url;
More information: you can check the full code at http://nopcommerce.codeplex.com/SourceControl/changeset/view/9125b9a7fafe#src%2fLibraries%2fNop.Services%2fMedia%2fPictureService.cs (please search the GetPictureUrl() function)
回答1:
This is a case that I have see when multi-request happens together for the same image.
For this case the lock is not enough, you need to use mutex to lock this procedure for all threads and all request together.
So what I suggest is to change the lock
, with mutex
and use the image name, or a code of the image as name for the mutex to not lock anything and any image that is going to made but only the one that is defined by the name on the mutex. So change the lock with mutex, and then see if this problem still exist.
one tip: The mutex name have some limitations on the size and the characters. If you use the image file name as the name for the mutex be sure that is accepted by mutex.
回答2:
Move check for file existence to be under the same s_lock
as file creation. Should solve the problem with partially completed file (if it is the problem).
If fixed - use @Aristos suggestion to replace lock (Monitor) with named Mutext to scope locking down to individual files (if you site is expected to have heavy load).
来源:https://stackoverflow.com/questions/10554928/image-caching-issue-by-using-files-in-asp-net