【问题标题】:HttpClient download file OutOfMemory ErrorHttpClient 下载文件 OutOfMemory 错误
【发布时间】:2014-04-16 13:01:49
【问题描述】:

您好,我将此代码用于文件下载器功能,但由于我的文件过大而收到 OutOfMemory 异常。

private async void DownloadFile()
    {

        string url = "http://download.microsoft.com/download/0/A/F/0AFB5316-3062-494A-AB78-7FB0D4461357/Windows_Win7SP1.7601.17514.101119-1850.AMD64CHK.Symbols.msi";
        string filename = "test.msi";

        HttpClientHandler aHandler = new HttpClientHandler();
        aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
        HttpClient aClient = new HttpClient(aHandler);
        aClient.DefaultRequestHeaders.ExpectContinue = false;
        HttpResponseMessage response = await aClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); // Important! ResponseHeadersRead.

        var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);

        Stream stream = await response.Content.ReadAsStreamAsync();
        IInputStream inputStream = stream.AsInputStream();
        ulong totalBytesRead = 0;
        while (true)
        {
            // Read from the web.
            IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);
            buffer = await inputStream.ReadAsync(
                buffer,
                buffer.Capacity,
                InputStreamOptions.None);

            if (buffer.Length == 0)
            {
                // There is nothing else to read.
                break;
            }

            // Report progress.
            totalBytesRead += buffer.Length;
            System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead);

            // Write to file.
            await fs.WriteAsync(buffer);

            buffer = null;

        }
        inputStream.Dispose();
        fs.Dispose();
    }

PS。我使用 httpclient 下载,但 Windows phone 后台传输有 100MB 的 wifi 限制。

【问题讨论】:

  • 我唯一能建议的是将写入流刷新到磁盘

标签: c# windows-phone httpclient


【解决方案1】:

我在去年处理的一些不同代码中也遇到了同样的问题,尽管那是POST 而不是GET。不幸的是,我没有找到解决方法,所以我直接使用WebRequest。这是修复中的一个 sn-p:

// HttpWebRequest is used here instead of HttpClient as there is no support
// in HttpClient to not buffer uploaded streams, which for our purposes
// causes an OutOfMemoryException to occur.
HttpWebRequest request = WebRequest.Create(ServiceUri.ToString() + requestUri) as HttpWebRequest;
request.ContentLength = content.Length;
request.ContentType = "application/octet-stream";
request.Method = "POST";

request.AllowWriteStreamBuffering = false;  // Prevents OutOfMemoryException

我认为您的解决方法是在使用 HttpClient 下载时以某种方式禁用缓冲。

【讨论】:

  • 这个方法是异步的?
  • 这是在 async 方法中使用的,是的,但上面的代码不是固有的 async。当您实际使用 request 对象做某事时,async 魔法就会出现。
  • 呃……微软!你怎么可能!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-01-11
  • 2019-07-15
相关资源
最近更新 更多