【问题标题】:WebAPI StreamContent vs PushStreamContentWebAPI StreamContent 与 PushStreamContent
【发布时间】:2013-04-16 15:04:51
【问题描述】:

我正在实施 MVC4 + WebAPI version of the BluImp jQuery File Upload 在我最初的尝试中一切正常,但我试图确保在下载非常大的文件 (~2GB) 时充分利用内存。

我已阅读 Filip Woj's article on PushStreamContent 并尽我所能实现它(删除异步部分 - 也许这是问题所在?)。当我运行测试并观看 TaskManager 时,我没有看到内存使用方面的太大差异,并且我试图了解响应处理方式之间的差异。

这是我的 StreamContent 版本:

private HttpResponseMessage DownloadContentNonChunked()
{
    var filename = HttpContext.Current.Request["f"];
    var filePath = _storageRoot + filename;
    if (File.Exists(filePath))
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = filename
        };
        return response;
    }
    return ControllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, "");
}

这是我的 PushStreamContent 版本:

public class FileDownloadStream
{
    private readonly string _filename;

    public FileDownloadStream(string filePath)
    {
        _filename = filePath;
    }

    public void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
    {
        try
        {
            var buffer = new byte[4096];

            using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
            {
                var length = (int)video.Length;
                var bytesRead = 1;

                while (length > 0 && bytesRead > 0)
                {
                    bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                    outputStream.Write(buffer, 0, bytesRead);
                    length -= bytesRead;
                }
            }
        }
        catch (HttpException ex)
        {
            return;
        }
        finally
        {
            outputStream.Close();
        }
    }
}

private HttpResponseMessage DownloadContentChunked()
{
    var filename = HttpContext.Current.Request["f"];
    var filePath = _storageRoot + filename;
    if (File.Exists(filePath))
    {
        var fileDownload = new FileDownloadStream(filePath);
        var response = Request.CreateResponse();
        response.Content = new PushStreamContent(fileDownload.WriteToStream, new MediaTypeHeaderValue("application/octet-stream"));
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = filename
        };
        return response;
    }
    return ControllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, "");
}

我的问题是为什么我没有看到这两种方法在内存使用方面有太大差异?此外,我已经下载了 StreamContent 类型的 PDB,并且可以看到对缓冲区大小等的引用(见下文),所以我想确切地知道 PushStreamContent 在 StreamContent 之外做什么。我检查了 MSDN 上的类型信息,但这篇文章的解释有点轻!

namespace System.Net.Http
{
  /// <summary>
  /// Provides HTTP content based on a stream.
  /// </summary>
  [__DynamicallyInvokable]
  public class StreamContent : HttpContent
  {
    private Stream content;
    private int bufferSize;
    private bool contentConsumed;
    private long start;
    private const int defaultBufferSize = 4096;

    /// <summary>
    /// Creates a new instance of the <see cref="T:System.Net.Http.StreamContent"/> class.
    /// </summary>
    /// <param name="content">The content used to initialize the <see cref="T:System.Net.Http.StreamContent"/>.</param>
    [__DynamicallyInvokable]
    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    public StreamContent(Stream content)
      : this(content, 4096)
    {
    }

【问题讨论】:

  • 我认为这些是相似的方法,只是分布不同。 "pure" .net 和 web api
  • 它们看起来确实很相似——这就是为什么我问我猜 PushStreamContent 会更加冗长,而他们也在做类似的事情,我想知道在这种情况下我应该使用哪个作为最佳实践!
  • 从我的测试中我看到 StreamContent 首先加载到内存中,然后刷新它。我建议不要将其用于大文件。你的 FileDownloadStream 很好。
  • 我想知道StreamContent 是否改变了行为。我认为旧版本的 WebAPI 会完全缓冲它,迫使人们使用 PushStreamContent 来解决这个问题,而现代版本的或者可能在 OWIN 下托管时根本不缓冲,使它们都等效。

标签: c# visual-studio asp.net-mvc-4 asp.net-web-api


【解决方案1】:

关于这两种方法的内存使用情况,对于 StreamContent 和 PushStreamContent,Web API 不会缓冲响应。以下代码快照来自 WebHostBufferPolicySelector。源码here.

    /// <summary>
    /// Determines whether the host should buffer the <see cref="HttpResponseMessage"/> entity body.
    /// </summary>
    /// <param name="response">The <see cref="HttpResponseMessage"/>response for which to determine
    /// whether host output buffering should be used for the response entity body.</param>
    /// <returns><c>true</c> if buffering should be used; otherwise a streamed response should be used.</returns>
    public virtual bool UseBufferedOutputStream(HttpResponseMessage response)
    {
        if (response == null)
        {
            throw Error.ArgumentNull("response");
        }

        // Any HttpContent that knows its length is presumably already buffered internally.
        HttpContent content = response.Content;
        if (content != null)
        {
            long? contentLength = content.Headers.ContentLength;
            if (contentLength.HasValue && contentLength.Value >= 0)
            {
                return false;
            }

            // Content length is null or -1 (meaning not known).  
            // Buffer any HttpContent except StreamContent and PushStreamContent
            return !(content is StreamContent || content is PushStreamContent);
        }

        return false;
    }

PushStreamContent 还适用于需要将数据“推送”到流的场景,其中 StreamContent 从流中“拉取”数据。因此,对于您当前下载文件的场景,使用 StreamContent 应该没问题。

以下示例:

// Here when the response is being written out the data is pulled from the file to the destination(network) stream
response.Content = new StreamContent(File.OpenRead(filePath));

// Here we create a push stream content so that we can use XDocument.Save to push data to the destination(network) stream
XDocument xDoc = XDocument.Load("Sample.xml", LoadOptions.None);
PushStreamContent xDocContent = new PushStreamContent(
(stream, content, context) =>
{
     // After save we close the stream to signal that we are done writing.
     xDoc.Save(stream);
     stream.Close();
},
"application/xml");

【讨论】:

  • 我想我遵循 - 那么在什么情况下你会使用 PushStreamContent 呢?
  • 所以如果我想在“流视频”这个词的意义上“流”内容使用 PushStreamContent 但如果我想让某人“下载文件”然后使用 StreamContent?还有其他注意事项吗?
  • 对,“流媒体视频”场景是一种,您不知道预先的总内容长度,并且您正在写入目标流,因为您正在从某个地方接收视频馈送。这就是使用 PushStreamContent 响应以分块传输编码发送的原因,因为我们预先不知道内容长度。
  • 对于其他使用 Owin 并想知道为什么无论他们做什么他们的响应都会被缓冲的人,在 5.1.0-RC1 中修复了 5.0.0 中与缓冲相关的错误。想我会分享,如果我在五个小时前知道的话,我可能还剩下一些头发。 update-package microsoft.aspnet.webapi.owin -includeprerelease 是你的朋友。
  • @bUKaneer:使用 PushStreamContent 的情况包括所有写入流的函数/对象。大多数序列化程序写出到流中。许多人写入内存流(这并不可怕,因为大多数序列化程序不是异步的,因此会阻塞线程)。另一种情况可能是 GZip 流,尽管我不记得它的接口 - 它可能需要写入目标流。 “流媒体视频”是一个应用程序级别的答案。我希望我的回答更有用。此外,流式视频可能是一个错误的答案——应该使用 UDP,而不是 HTTP/TCP。
猜你喜欢
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 2014-08-22
  • 1970-01-01
  • 2016-07-26
相关资源
最近更新 更多