Stream.ReadAsync()在第一次调用时非常慢

时间:2016-01-12 11:10:32

标签: c# windows-runtime windows-phone-8.1

我正在编写一个类来处理文件下载,我正在使用此代码[简化]:

var webRequest = (HttpWebRequest)WebRequest.Create(downloadOperation.Link);
webRequest.Proxy = null;
using (var webResponse = await webRequest.GetResponseAsync())
{
    using (var downloadStream = webResponse.GetResponseStream())
    {
        using (var outputFileWriteStream = await outputFile.OpenStreamForWriteAsync())
        {
            var buffer = new byte[4096];
            var downloadedBytes = 0;
            var totalBytes = webResponse.ContentLength;
            while (downloadedBytes < totalBytes)
            {
                //*************************THIS LINE TAKES ABOUT 32 SECONDS TO EXECUTE ON FIRST INVOKE, ALL NEXT INVOKES TAKE ABOUT 120MS***************************
                var currentRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length);
                //*******************************************************************************************************************************************************************

                await outputFileWriteStream.WriteAsync(buffer, 0, currentRead); 
            }
        }
    }
}

你可以向我解释一下为什么第一次调用而不是下一次调用需要很长时间?我担心它会在第一次阅读时下载整个文件。

请注意,文件通常在3~15MB之间。

2 个答案:

答案 0 :(得分:1)

  

我担心它会在第一次阅读时下载整个文件。

这正是发生的事情。您可以通过将webRequest.AllowReadStreamBuffering设置为false来更改它。

答案 1 :(得分:0)

所以我找到了解决此问题的方法,但它没有使用WebRequest类。

我现在正在使用(Windows.Web.Http)中的HttpClient。

这是固定代码:

    var client = new Windows.Web.Http.HttpClient(); // prepare the http client 

//get the response from the server
using (var webResponse = await client.GetAsync(downloadOperation.Link, HttpCompletionOption.ResponseHeadersRead)) //***********Node the HttpCompletionOption.ResponseHeaderRead, this means that the operation completes as soon as the client receives the http headers instead of waiting for the entire response content to be read
{
    using (var downloadStream = (await webResponse.Content.ReadAsInputStreamAsync()).AsStreamForRead() )
    {
        using (var outputFileWriteStream = await outputFile.OpenStreamForWriteAsync())
        {
            var buffer = new byte[4096];
            var downloadedBytes = 0;
            var totalBytes = webResponse.ContentLength;
            while (downloadedBytes < totalBytes)
                {
                    //*************************THIS LINE NO LONGER TAKES A LONG TIME TO PERFORM FIRST READ***************************
                    var currentRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length);
                    //*******************************************************************************************************************************************************************

                    await outputFileWriteStream.WriteAsync(buffer, 0, currentRead); 
                }
        }

    }

}

希望这会帮助那里的人;)

谢谢大家