C#下载速度异步 [英] C# Download Speed Asynchronously

查看:204
本文介绍了C#下载速度异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取当前用户的网络下载速度。击中NetworkInterfaces一条死胡同后,所有我试图解决我在网上找到。我编辑它一下,它的伟大工程,但它不是异步的。

I'm trying to get the current user's network download speed. After hitting a dead end with NetworkInterfaces and all I tried a solution I found online. I edited it a bit and it works great but it's not asynchronous.

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分钟为间隔定时器内。

That function is called within a timer at an interval of 2 minutes.

MyLbl.GetDownloadSpeed()

我已经使用WebClient.DownloadFileAsync尝试,但只是展示了无限symbol.My下试试是使用HttpClient的,但是我走之前没有任何人有当前用户的下载速度越来越异步的推荐方法(没有落后的主界面线程)?

I've tried using WebClient.DownloadFileAsync but that just shows the unlimited symbol.My next try would be to use HttpClient but before I go on does anyone have a recommended way of getting the current users download speed asynchronously (without lagging the main GUI thread)?

推荐答案

由于有人建议你可以让的异步版本GetDownloadSpeed()

As it was suggested you could make an async version of GetDownloadSpeed():

    async void GetDownloadSpeedAsync(this Label lbl, Uri address, int numberOfTests)
    {
        string directoryName = @"C:\Work\Test\speedTest";
        string fileName = "tmp.dat";

        if (!Directory.Exists(directoryName))
            Directory.CreateDirectory(directoryName);

        Stopwatch timer = new Stopwatch();

        timer.Start();

        for (int i = 0; i < numberOfTests; ++i)
        {
            using (WebClient client = new WebClient())
            {
                await client.DownloadFileTaskAsync(address, Path.Combine(directoryName, fileName), CancellationToken.None);
            }
        }

        lbl.Text == Convert.ToString(timer.Elapsed.TotalSeconds / numberOfTests);
    }



WebClient类是比较老不具有的 awaitable DownloadFileAsync()

EDITED
由于这是正确地指出,其实Web客户端有一个基于任务的异步方法DownloadFileTaskAsync(),我建议它使用。下面的代码仍然可以帮助解决的情况下异步方法返回工作未提供。

我们可以修复它与 TaskCompletionSource<的帮助; T>

    public static class WebClientExtensions
    {

        public static Task DownloadFileAwaitableAsync(this WebClient instance, Uri address, 
            string fileName, CancellationToken cancellationToken)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();

            // Subscribe for completion event
            instance.DownloadFileCompleted += instance_DownloadFileCompleted;

            // Setup cancellation
            var cancellationRegistration = cancellationToken.CanBeCanceled ? (IDisposable)cancellationToken.Register(() => { instance.CancelAsync(); }) : null;

            // Initiate asyncronous download 
            instance.DownloadFileAsync(address, fileName, Tuple.Create(tcs, cancellationRegistration));

            return tcs.Task;
        }

        static void instance_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            ((WebClient)sender).DownloadDataCompleted -= instance_DownloadFileCompleted;
            var data = (Tuple<TaskCompletionSource<object>, IDisposable>)e.UserState;
            if (data.Item2 != null) data.Item2.Dispose();
            var tcs = data.Item1;

            if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else
            {
                tcs.TrySetResult(null);
            }
        }
    }

这篇关于C#下载速度异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆