gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:21 25 4
gpt4 key购买 nike

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 事件?

最佳答案

  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 + "%");
}
}
}

关于c# - 如何在 C# 中检查 Httpclient 下载速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47033018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com