1

一些背景

我有一个 ASP.net MVC 4 Web 应用程序,它提供对大量照片的访问。每张照片都有一个来自 MySQL 表的唯一 ID,然后以十六进制形式组成文件名并存储在文件系统上的文件夹中。

例如:

D:\照片\69F.jpg

在整个应用程序中,会显示使用原始照片创建的不同大小的缩略图。由于缩略图很少更改,如果有的话,缩略图会创建并以以下格式保存到相同的文件系统文件夹中。(这意味着在 90% 的情况下,照片可以直接返回,无需任何图像处理)。

  • 缩略图正常- D:\Photos\69F_t.jpg
  • 缩略图- D:\Photos\69F_tm.jpg

所有照片都通过一个特殊的控制器(ImageController)访问,这个控制器有许多动作,具体取决于所需的缩略图类型。例如,如果需要普通缩略图,则必须调用Thumb操作,然后确定缩略图是否存在,如果不存在,则在将其返回给浏览器之前创建并保存它。

\图像\拇指\ 1695

该应用程序在对上述文件夹具有完全访问权限的帐户下运行,并且由于大多数情况下可以正常工作,因此这不是权限问题!

问题

我遇到的问题是,在调用获取缩略图时,应用程序会报告零星错误。错误都遵循以下格式,但照片 ID 当然会发生变化(即,它发生在超过 1 张照片上):

该进程无法访问文件“D:\Photos\69F_t.jpg”,因为它正被另一个进程使用。

或者...

拒绝访问路径“D:\Photos\69F_t.jpg”。

上述错误均源自最后的Try...Catch中的Return File(...)行:

Function Thumb(Optional ByVal id As Integer = Nothing)

    Dim thumbImage As WebImage
    Dim dimension As Integer = 200

    ' Create the image paths
    Dim imageOriginal As String = System.Configuration.ConfigurationManager.AppSettings("imageStore") + Hex(id) + ".jpg"
    Dim imageThumb As String = System.Configuration.ConfigurationManager.AppSettings("imageStore") + Hex(id) + "_t.jpg"

    ' If no image is found, return not found
    If FileIO.FileSystem.FileExists(imageOriginal) = False Then
        Return New HttpNotFoundResult
    End If

    ' If a thumbnail is present, check its validity and return it
    If FileIO.FileSystem.FileExists(imageThumb) = True Then
        thumbImage = New WebImage(imageThumb)

        ' If the dimensions are correct, simply return the image
        If thumbImage.Width = dimension Then
            thumbImage = Nothing
            Return File(imageThumb, System.Net.Mime.MediaTypeNames.Image.Jpeg)
        End If
    End If

    ' If we get this far, either the thumbnail is not the right size or does not exist!
    thumbImage = New WebImage(imageOriginal)

    ' First we must make the image a square
    If thumbImage.Height > thumbImage.Width Then
        ' Portrait
        Dim intPixelRemove As Integer

        ' Determine the amount to crop off the top and bottom
        intPixelRemove = (thumbImage.Height - thumbImage.Width) / 2
        thumbImage.Crop(intPixelRemove, 0, intPixelRemove, 0)
    Else
        ' Landscape
        Dim intPixelRemove As Integer

        ' Determine the amount to crop off the top and bottom
        intPixelRemove = (thumbImage.Width - thumbImage.Height) / 2
        thumbImage.Crop(0, intPixelRemove, 0, intPixelRemove)
    End If

    thumbImage.Resize(dimension + 2, dimension + 2, True, True)
    thumbImage.Crop(1, 1, 1, 1)
    thumbImage.Save(imageThumb)
    thumbImage = Nothing

    Try
        Return File(imageThumb, System.Net.Mime.MediaTypeNames.Image.Jpeg)
    Catch ex As Exception
        Return New HttpNotFoundResult
    End Try

End Function

问题

我很确定有些东西让文件保持打开状态,所以不会让应用程序将文件返回给浏览器,但不管它是什么,它都非常零星,因为这在 90-95% 的调用中都可以正常工作。

要么是这个问题,要么是由于超过 1 个人试图访问同一个文件而导致的并发问题。

  1. 谁能发现可能导致这种情况的原因?
  2. 如果多人同时尝试访问同一张照片缩略图,我是否可能会遇到更多问题?
4

0 回答 0