वेबक्लिएंट क्लास निम्न कोड के साथ गति को मापने में सक्षम था:
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 प्रोग्रेस चेंज किए गए ईवेंट के बिना अब तक प्राप्त बाइट्स को नहीं जानता है।
क्या HttpClient में यह जानने के लिए कोई तरीका है कि अब तक कितने बाइट प्राप्त हुए हैं, जैसे वेब क्लाइंट की प्रोग्रेस चेंजेड इवेंट?
उत्तर:
जवाब के लिए 0 № 1 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 + "%");
}
}
}