WebRequest.GetRequestStream and LOH

守給你的承諾、 提交于 2020-01-02 15:31:12

问题


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
                }
            }

Memory profiler graph. bytes array create internally in GetRequestStream


回答1:


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);
    }


来源:https://stackoverflow.com/questions/13052679/webrequest-getrequeststream-and-loh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!