gpt4 book ai didi

c# - WebRequest.GetRequestStream 和 LOH

转载 作者:太空宇宙 更新时间:2023-11-03 11:14:35 25 4
gpt4 key购买 nike

我正在使用下面的代码将大文件上传到服务器,并注意到将 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 内部创建字节数组

Memory profiler graph. bytes array create internally in GetRequestStream

最佳答案

您可以使用 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);
}

关于c# - WebRequest.GetRequestStream 和 LOH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13052679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com