How can I get my upload speed with HttpClient

旧时模样 提交于 2021-02-05 12:14:20

问题


I'm using HttpClient to post a byte array to a server. How can I tell how many bytes are transferred per second?


回答1:


The simplest, naive way to do it is to use the Stopwatch class to get the interval before and after your HttpClient.PostAsync call, then divide that time by the payload size:

byte[] payload = GetData();
var content = new ByteArrayContent(payload);
var stopwatch = Stopwatch.Start();
await httpClient.PostAsync(url, content);
stopwatch.Stop();
var bps = payload.Length / stopwatch.Elapsed.TotalSeconds;

This is a primitive method, because it doesn't count how long it took for the actual bytes to make it through the network interface, but the total, inclusive time it took the HttpClient class to perform the POST operation - including allocating memory, spinning up threads if necessary, the mechanics of the async/await operations and so on. However, in most cases, these are all noticeably faster than the actual I/O, so it might be negligible - it depends on how accurate you need your results.

A more accurate way can be done using the NetworkInterface class to check the BytesSent counter, which can be found here:

  • How to get accurate download/upload speed in C#.NET?


来源:https://stackoverflow.com/questions/50886000/how-can-i-get-my-upload-speed-with-httpclient

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!