如何在C#中检查Httpclient下载速度?

时间:2017-10-31 10:25:20

标签: c# httpclient

Webclient类能够使用以下代码测量速度:

    ConcurrentQueue<long> bytes = new ConcurrentQueue<long>();
    long before = 0;
    private async void WebClientDownload(string url,string filepath)
    {
        using (WebClient client = new WebClient())
        {
            client.DownloadProgressChanged += (sender, e) =>
            {
                bytes.Enqueue(e.BytesReceived - before);
                before = e.BytesReceived;                   
            };
            await client.DownloadFileTaskAsync(url, filepath);
        }
    }
    private async void MeasureSpeed()
    {
        while(true)
        {
            long val,sum = 0;
            while (bytes.TryDequeue(out val)) sum += val;
            sum /= 1024;
            //Print : Speed= sum KB/s
            await Task.Delay(1000);
        }
    }

但是,由于Httpclient类似乎更快,我想使用这个类。与WebClient不同,HttpClient在没有ProgressChanged事件的情况下不知道它到目前为止收到的字节。

HttpClient中是否有办法知道到目前为止收到了多少字节,例如WebClient的ProgressChanged事件?

1 个答案:

答案 0 :(得分:0)

  HttpClient client = new HttpClient();

            using (var stream = await client.GetStreamAsync(url))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] buffer = new byte[1024];
                    Console.WriteLine("Download Started");
                    totalBytes = client.MaxResponseContentBufferSize;

                    for (; ; )
                    {
                        int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            await Task.Yield();
                            break;
                        }

                        receivedBytes += bytesRead;

                        int received = unchecked((int)receivedBytes);
                        int total = unchecked((int)totalBytes);

                        double percentage = ((float)received) / total;
                        Console.WriteLine(received / (1024) + "Kb / " + total / (1024 )+" Kb");
                        Console.WriteLine("Completed : " + percentage + "%");
                    }
                }
            }