Archived Forum Post

Index of archived forum posts

Question:

C# HTTP DownloadAync BytesPerSec

Jan 09 '16 at 07:40

How can I pull the bytes per sec transfer speed when using DownloadAsync? I had iterated through the http eventlog before for "RecvBytesPerSec", but this does not seem to exist in the task ProgressInfo


Answer

The Async methods should still fire events, so you can get the SendRate/ReceiveRate events, but beware because the events will be called in the background thread. In other words, when your event handler is called, it's in a background thread and you cannot just update a UI element. If you need to update UI elements from the bg thread, use MethodInvoker. See http://www.cknotes.com/vb-net-taskcompleted-event-for-asynchronous-method-call/


Answer

Hello, Thanks for responding, however I am not seeing any events get invoked.

    public bool Download(string url, string destinationPath, bool unzip)
    {

        _http.KeepEventLog = true;
        _http.EnableEvents = true;
        _http.OnReceiveRate += _http_OnReceiveRate;
        Task task = _http.DownloadAsync(url, destinationPath);
        task.OnProgressInfo += task_OnProgressInfo;
        task.OnPercentDone += task_OnPercentDone;
        task.KeepProgressLog = true;
        task.EnableEvents = true;

        task.Run();

        while (!task.Finished)
        {

            while (task.ProgressLogSize > 0)
            {
                string logName = task.ProgressInfoName(0);
                string logValue = task.ProgressInfoValue(0);
                task.RemoveProgressInfo(0);
                Debug.Print(logName);
                if (logName.Contains("RecvBytesPerSec"))
                {
                    double bytesPerSec;
                    if (double.TryParse(logValue, out bytesPerSec) == false)
                        bytesPerSec = 0;

                    string transferSpeed = ConvertBytesToTransferSpeed(bytesPerSec);
                    Debug.Print("Speed: " + transferSpeed);
                }
                else if (logName.Contains("PercentDone"))
                {
                    double percentDone;
                    if (double.TryParse(logValue, out percentDone) == false)
                        percentDone = 100.0;

                    Debug.Print("Percent: " + percentDone);
                }
            }

            task.SleepMs(100);
        }

        return true;

    }

    void _http_OnReceiveRate(object sender, DataRateEventArgs args)
    {
        Debug.Print(args.BytesPerSec.ToString());
    }

    void task_OnPercentDone(object sender, PercentDoneEventArgs args)
    {
        Debug.Print(args.PercentDone.ToString());
    }

    private void task_OnProgressInfo(object sender, ProgressInfoEventArgs args)
    {
        Debug.Print(args.Name + " " + args.Value);
    }

Answer

Try registering the event on the http-object instead of the task-object.