如何在ASP.NET MVC 3中从下载的文件中优化内存zip存档创建

时间:2012-06-07 10:09:53

标签: c# asp.net .net asp.net-mvc

我正在制作一个控制器,它应该返回从另一台服务器下载的文件的压缩列表(放在同一个数据中心)

我为妈妈所做的一切:

/// <summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
/// </summary>
/// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
public override void ExecuteResult(ControllerContext context)
{
    context.HttpContext.Response.ContentType = "application/zip";
    context.HttpContext.Response.CacheControl = "private";
    context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    context.HttpContext.Response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", this.ResultFileName));

    var buffer = new byte[BufferSize];

    using (var zippedUploadStream = new ZipOutputStream(context.HttpContext.Response.OutputStream))
    {
        zippedUploadStream.SetLevel(0);

        foreach (var url in this.Urls)
        {
            var request = WebRequest.Create(url);
            var response = request.GetResponse();
            var downloadStream = response.GetResponseStream();

            if (downloadStream != null)
            {
                var zipEntry = new ZipEntry(Path.GetFileName(response.ResponseUri.ToString()));
                zippedUploadStream.PutNextEntry(zipEntry);

                int read;
                while ((read = downloadStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    zippedUploadStream.Write(buffer, 0, read);
                    context.HttpContext.Response.Flush();
                }
            }

            if (!context.HttpContext.Response.IsClientConnected)
            {
                break;
            }
        }

        zippedUploadStream.Finish();
    }

    context.HttpContext.Response.Flush();
    context.HttpContext.Response.End();
}

令我感到可怕的是,所有操作都是同步的。

如果我要离开这个实施,那么这个问题会有多难?

是否可以从另一个线程访问context.HttpContext.Response对象?

可以使用异步调用优化此代码吗?

1 个答案:

答案 0 :(得分:0)

您真的不想在Web请求线程中执行这样的任务。这些类型的长期运行,系统资源密集型任务最好使用某种排队或消息总线系统来执行。我推荐NServiceBus之类的东西来完成这项任务。您可以使用NServiceBus将消息排入队列,而不是从单个Web请求线程中同步创建多个Web请求。然后,NServiceBus将接收每个消息(可能是异步,取决于配置)并单独处理它们。这样做可以获得MSMQ的可靠性和持久性优势,NServiceBus将其用作消息队列。