2

我正在使用下面的代码将大文件上传到服务器,并注意到将 FileStream 复制到 GetRequestStream 字节数组被创建并保存在内存中。这增加了大对象堆,我不想要它。也许有人知道如何解决这个问题?

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 内部创建

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

4

1 回答 1

2

您可以使用HttpWebRequest.AllowWriteStreamBuffering禁用内部缓冲:

    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);
    }
于 2012-10-24T15:53:44.317 回答