簡體   English   中英

對 Stream 大文件使用 HttpWebRequest 時出現 Memory 異常

[英]Out of Memory Exception When Using HttpWebRequest to Stream Large File

使用大文件的 Http.Put 時出現 Out of Memory 異常。 如代碼所示,我正在使用異步 model。 我正在嘗試將 8K 數據塊發送到 Windows 2008 R2 服務器。 當我嘗試寫入超過 536,868,864 字節的數據塊時,始終會發生異常。 異常發生在下面代碼片段中的 requestStream.Write 方法上。

尋找原因?

注意:較小的文件可以放置。 如果我寫入本地 FileStream,邏輯也可以工作。 在 Win 7 Ultimate 客戶端計算機上運行 VS 2010、.Net 4.0。

   HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Http://website/FileServer/filename");
   request.Method = WebRequestMethods.Http.Put;
   request.SendChunked = true;
   request.AllowWriteStreamBuffering = true;
   ...

   request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state);
   ...

   int chunk = 8192; // other values give same result
   ....

   private static void EndGetStreamCallback(IAsyncResult ar) {
        long limit = 0;
        long fileLength;
        HttpState state = (HttpState)ar.AsyncState;

        Stream requestStream = null;
        // End the asynchronous call to get the request stream.

        try {
            requestStream = state.Request.EndGetRequestStream(ar);
            // Copy the file contents to the request stream.

            FileStream stream = new FileStream(state.FileName, FileMode.Open, FileAccess.Read, FileShare.None, chunk, FileOptions.SequentialScan);

            BinaryReader binReader = new BinaryReader(stream);
            fileLength = stream.Length;

            // Set Position to the beginning of the stream.
            binReader.BaseStream.Position = 0;

            byte[] fileContents = new byte[chunk];

            // Read File from Buffer 
            while (limit < fileLength)
            {
                fileContents = binReader.ReadBytes(chunk);

                // the next 2 lines attempt to write to network and server
                requestStream.Write(fileContents, 0, chunk);   // causes Out of memory after 536,868,864 bytes
                requestStream.Flush();  // I get same result with or without Flush

                limit += chunk;
            }

            // IMPORTANT: Close the request stream before sending the request.
            stream.Close();

            requestStream.Close();
        }
    }

您顯然有這個記錄在案的問題 AllowWriteStreamBufferingtrue時,它會緩沖寫入請求的所有數據,因此,“解決方案”是將該屬性設置為false

要解決此問題,請將 HttpWebRequest.AllowWriteStreamBuffering 屬性設置為 false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM