1

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)

4

2 回答 2

2

这是我看到的一个例子,当多个请求同时发生在同一个图像上时。

对于这种情况,锁是不够的,你需要使用互斥锁来为所有线程和所有请求一起锁定这个过程。

因此,我建议更改 lock, withmutex并使用图像名称或图像代码作为互斥锁的名称,以不锁定任何东西和任何将要制作的图像,但只锁定由名称定义的图像互斥体。于是用mutex换了锁,然后看看这个问题是否还存在。

一个提示:互斥锁名称对大小和字符有一些限制。如果您使用图像文件名作为互斥锁的名称,请确保它被互斥锁接受。

于 2012-05-11T16:23:07.437 回答
0

将文件存在的检查移到与s_lock文件创建相同的位置。应该解决部分完成文件的问题(如果是问题)。

如果已修复 - 使用 @Aristos 建议将锁定(监视器)替换为命名的 Mutext 以将锁定范围锁定到单个文件(如果您的站点预计负载很重)。

于 2012-05-11T16:30:16.770 回答