【发布时间】:2015-08-13 14:32:57
【问题描述】:
我正在尝试获取当前用户的网络下载速度。在使用 NetworkInterfaces 遇到死胡同后,我尝试了在网上找到的解决方案。我对其进行了一些编辑,效果很好,但它不是异步的。
public static void GetDownloadSpeed(this Label lbl)
{
double[] speeds = new double[5];
for (int i = 0; i < 5; i++)
{
int fileSize = 407; //Size of File in KB.
WebClient client = new WebClient();
DateTime startTime = DateTime.Now;
if (!Directory.Exists($"{CurrentDir}/tmp/speedtest"))
Directory.CreateDirectory($"{CurrentDir}/tmp/speedtest");
client.DownloadFile(new Uri("https://ajax.googleapis.com/ajax/libs/threejs/r69/three.min.js"), "/tmp/speedtest/three.min.js");
DateTime endTime = DateTime.Now;
speeds[i] = Math.Round((fileSize / (endTime - startTime).TotalSeconds));
}
lbl.Text = string.Format("{0}KB/s", speeds.Average());
}
该函数在计时器内以 2 分钟的间隔被调用。
MyLbl.GetDownloadSpeed()
我尝试过使用 WebClient.DownloadFileAsync 但这只是显示无限符号。我的下一个尝试是使用 HttpClient 但在我继续之前,有没有人推荐一种异步获取当前用户下载速度的方法(不落后于主 GUI 线程)?
【问题讨论】:
-
您应该包含您尝试使用
DownloadFileAsync的代码。我怀疑你在结果任务的某处调用Result或Wait导致了死锁。 -
试试 `await Task.Run(()=> { //你的代码 });
-
谢谢@PhilippeParé 成功了!
-
@DanielKelley 我将方法设为异步并在其上调用了 await。
-
@PhilippeParé 您能否将您的评论作为答案,以便我将其标记为答案?
标签: c# asynchronous