0

我在使用 EF5 和 MVC3 从数据库流式传输小图像时遇到问题

当我流出 1 张图片时效果很好,但是当一个页面包含 5 张这样的图片时,它就像胶水一样,即使每张只有 5-200kb 大,它们也需要 5 秒才能加载。

在此处输入图像描述

我阅读了一些帖子并将其添加到 web.config

<system.net> 
  <connectionManagement> 
    <add address="*" maxconnection="100" /> 
  </connectionManagement> 
</system.net> 

它对我的问题没有任何影响。

并将其用于流式传输:

 public class ImageResult : ActionResult
    {
        public ImageResult(Stream imageStream, string contentType)
        {
            if (imageStream == null)
                throw new ArgumentNullException("imageStream");
            if (contentType == null)
                throw new ArgumentNullException("contentType");

            this.ImageStream = imageStream;
            this.ContentType = contentType;
        }

        public Stream ImageStream { get; private set; }
        public string ContentType { get; private set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = this.ContentType;

            byte[] buffer = new byte[4096];
            while (true)
            {
                int read = this.ImageStream.Read(buffer, 0, buffer.Length);
                if (read == 0)
                    break;

                response.OutputStream.Write(buffer, 0, read);
            }

            response.End();
        }
    }

更新

我删除了 ImageResult 并添加了返回文件......加快了速度,但速度仍然不可接受...... 18kb 文件需要 2 秒。

控制器:

   [SessionState(SessionStateBehavior.Disabled)]
   public class ContentController : Controller
    {
    .....
       public ActionResult Thumbnail(int fileID, int width)
       {
           var thumbnail = _fileRep.GetThumbnail(fileID, width);

           return File(thumbnail.FileContent, thumbnail.ContentType);
        }
4

1 回答 1

2

您面临的问题很可能是由于每个会话对 ASP.NET 会话状态的访问是独占的。这意味着如果对同一个会话(通过使用相同的 SessionID 值)发出两个并发请求,则第一个请求将获得对会话信息的独占访问权。第二个请求仅在第一个请求完成后执行。您可以在此处阅读有关它的更多信息:ASP.NET 会话状态概述并发请求和会话状态部分)

如果您的图像操作方法不需要访问会话,您可以通过使用SessionStateAttribute属性装饰控制器来解决您的问题:

[SessionState(SessionStateBehavior.Disabled)]

这将允许控制器以“并行”方式处理请求。

如果您需要对会话进行读取访问,您可以尝试使用该SessionStateBehavior.ReadOnly值。这不会导致独占锁,但请求仍需等待读写请求设置的锁。

于 2013-03-26T08:27:04.517 回答