• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

WebRequest.GetRequestStream和LOH

用户头像
it1352
帮助1

问题说明

我使用跌破code到大文件上传到服务器,发现复制的FileStream到GetRequestStream创建字节数组,并保留在内存中。这一增长的大对象堆,我不希望它。也许有人知道如何解决这个问题?

I am using code below to upload large file to server and noticed that copying FileStream to GetRequestStream the bytes array is created and hold in memory. This increase large object heap and I don't want it. Maybe someone know how to solve this?

Stream formData = new FileStream(.....)

    HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
    using (Stream requestStream = request.GetRequestStream())
    {             
     Helpers.CopyStream(formData, requestStream);
     requestStream.Close();
    }

     public static void CopyStream(Stream fromStream, Stream toStream)
            {
                try
                {
                    int bytesRead;
                    byte[] buffer = new byte[32768];
                    while (fromStream != null && (bytesRead = fromStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        toStream.Write(buffer, 0, bytesRead);
                    }
                }
                catch (IOException)
                {
                    //suppress empty stream response
                }
            }

内存分析器图。字节数组中GetRequestStream内部创建

Memory profiler graph. bytes array create internally in GetRequestStream

学新通

正确答案

#1

您可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowwritestreambuffering.aspx"相对=nofollow> HttpWebRequest.AllowWriteStreamBuffering 禁用内部缓冲:

You can use the HttpWebRequest.AllowWriteStreamBuffering to disable internal buffering:

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

    request.AllowWriteStreamBuffering = false;

    using (Stream formData = File.Open(fileName, FileMode.Open))
    using (Stream requestStream = request.GetRequestStream())
    {
        formData.CopyTo(requestStream, 32768);
    }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjech
系列文章
更多 icon
同类精品
更多 icon
继续加载