StreamContent和ByteArrayContent webApi的差异 [英] Differences in StreamContent and ByteArrayContent webApi

查看:816
本文介绍了StreamContent和ByteArrayContent webApi的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网上搜索了所有内容,但找不到答案。
我们的应用程序中有两种方法:

I have searched all over the web, but not able to find the answer. We have two methods in our application:

a)第一个返回 HttpResponseMessage ,其中包含1个文件。它使用 StreamContent

a) First one return HttpResponseMessage with 1 file inside. It uses StreamContent.

 response.Content = new StreamContent(memStream);
 response.Content.Headers.ContentLength = memStream.Length;

b)第二个返回 HttpResponseMessage 包括zipp -ed文件(已压缩的多个文件)。

b) Second one return HttpResponseMessage including zipp-ed files (multiple files that are zipped). it uses ByteArrayContent.

response.Content = new ByteArrayContent(memStream.ToArray());
response.Content.Headers.ContentLength = memStream.ToArray().Length;

我只是想了解为什么在我们的应用程序中,当只返回一个文件而使用ByteArrayContent时使用StreamContent的原因返回压缩文件时。有没有逻辑,在两种情况下我都可以更改为使用相同的方式?

I just wanted to understand why in our application StreamContent is used when returning just one file and ByteArrayContent is used when returning zip-ed file. Is there some logic there or not and I can change to use the same way in both situations?

推荐答案

没有任何要备份的内容根据我的假设,除了传闻之外,流应该比字节数组更有效(它们基本上一次使用较小的字节缓冲区)。

Without anything to back up my assumption other than hearsay, streams are supposed to be more efficient than byte arrays (they basically work with smaller buffers of bytes at a time).

Web应用程序,我相信流传输将变得更加高效,因为它允许消费者在页面可用时实际分页下载页面,而不是等待所有内容在内存中准备就绪。

In the case of a web app, I believe streaming becomes even more efficient as it allows the consumer to actually download the page in pieces as it becomes available, rather than wait for all of the content to become ready in memory.

但是看起来您的应用在两种情况下都使用了 MemoryStream ,因此实际上来说,这可能并没有多大区别(因为内存流是围绕字节数组的包装...在内存中)。但是,它两次调用 memStream.ToArray(),效率较低,因为它第二次将其内部缓冲区复制到新数组中只是为了获取其长度(您可以直接使用 memStream.Length 调用。

But it looks like your app is using a MemoryStream in both cases, and so practically speaking it might not make much of a difference (because the memory stream is a wrapper around a byte array...in memory). It is however calling memStream.ToArray() twice, which is less efficient as it copies its internal buffer to a new array a second time just to get its length (which you can call directly with memStream.Length.

当然,不知道应用程序其余部分在做什么,也许有理由在提供数据之前先封送所有压缩数据。

Of course, without knowing what the rest of the app is doing, maybe there's a reason for it to marshal all of the zipped data before providing it.

这篇关于StreamContent和ByteArrayContent webApi的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆