Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9043545
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T10:45:19+00:00 2026-06-16T10:45:19+00:00

I’m currently writing a class to calculate the average download speed over a defined

  • 0

I’m currently writing a class to calculate the average download speed over a defined period of time, taking a defined number of samples. The way I thought this would work is that this class runs a Timer object, which calls a method inside said class that will look at the bytes downloaded (maintained in a parent class, the FTPDownloadFile), and then store that sample in a Queue. My issue is accessing the number of bytes downloaded, however.

My method of accessing that information was through a reference that was passed in when the download calculating class was constructed, however, it seems like I’m not understanding/using references correctly. The variable that is passed in always appears to be 0, even though I can see the original variable changing.

Can anyone tell me what I’m doing wrong / suggest a better way for me to accomplish what I want to do?

First, here is the class that is handling the calculation of the download speed:

public class SpeedCalculator
    {
        private const int samples = 5;
        private const int sampleRate = 1000; //In milliseconds
        private int bytesDownloadedSinceLastQuery;
        private System.Threading.Timer queryTimer;
        private Queue<int> byteDeltas = new Queue<int>(samples);
        private int _bytesDownloaded;

        public SpeedCalculator(ref int bytesDownloaded)
        {
            _bytesDownloaded = bytesDownloaded;
        }

        public void StartPolling()
        {
            queryTimer = new System.Threading.Timer(this.QueryByteDelta, null, 0, sampleRate);
        }

        private void QueryByteDelta(object data)
        {
            if (byteDeltas.Count == samples)
            {
                byteDeltas.Dequeue();
            }

            byteDeltas.Enqueue(_bytesDownloaded - bytesDownloadedSinceLastQuery);
            bytesDownloadedSinceLastQuery = _bytesDownloaded;
        }

        /// <summary>
        /// Calculates the average download speed over a predefined sample size.
        /// </summary>
        /// <returns>The average speed in bytes per second.</returns>
        public float GetDownloadSpeed()
        {
            float speed;
            try
            {
                speed = (float)byteDeltas.Average() / ((float)sampleRate / 1000f);
            }
            catch {speed = 0f;}

            return speed;
        }

That class is contained inside of my FTPDownloadFile class:

class FTPDownloadFile : IDisposable
{
    private const int recvBufferSize = 2048;
    public int bytesDownloaded;
    public SpeedCalculator Speed;
    private FileStream localFileStream;
    FtpWebResponse ftpResponse;
    Stream ftpStream;
    FtpWebRequest ftpRequest;
    public List<string> log = new List<string>();
    private FileInfo destFile;

    public event EventHandler ConnectionEstablished;

    public FTPDownloadFile()
    {
        bytesDownloaded = 0;
        Speed = new SpeedCalculator(ref bytesDownloaded);
    }

    public void GetFile(string host, string remoteFile, string user, string pass, string localFile)
    {
        //Some code to start the download...
        Speed.StartPolling();
    }

    public class SpeedCalculator {...}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T10:45:20+00:00Added an answer on June 16, 2026 at 10:45 am

    This is a common ‘issue’ with understanding ‘ref’ parameters in C#. You see, unlike C+, there are no real value references in C#.

    In C++, when you pass-by-reference, you actually internally pass pointer to the variable. Therefore, you can have a class member variable of type “int&” that is actual reference to an integer stored elsewhere.

    In C#, ‘ref’ or ‘out’ parameter works in a similar way, but noone talks about pointers. You cannot store the reference. You cannot have a ‘ref’ class member. Look at your class: the sotrage variable is of type ‘int’, plain ‘int’, not a reference.

    You actually are passing that value by-ref, but then you copy it to the member variable. The ‘reference’ is gone at the point where your constructor ends.

    To walk it around, you have to keep the actual source object, and either introduce a strong dependency, or a weak one by an interface, or do it lazy/functional way – by a delegate

    Ex#1: strong reference

    public class SpeedCalculator
    {
        private const int samples = 5;
        private const int sampleRate = 1000; //In milliseconds
        private int bytesDownloadedSinceLastQuery;
        private System.Threading.Timer queryTimer;
        private Queue<int> byteDeltas = new Queue<int>(samples);
    
        private FTPDownloadFile downloader; // CHANGE
    
        public SpeedCalculator(FTPDownloadFile fileDownloader) // CHANGE
        {
            downloader = fileDownloader;
        }
    
        public void StartPolling()
        {
            queryTimer = new System.Threading.Timer(this.QueryByteDelta, null, 0, sampleRate);
        }
    
        private void QueryByteDelta(object data)
        {
            if (byteDeltas.Count == samples)
            {
                byteDeltas.Dequeue();
            }
    
            byteDeltas.Enqueue(_bytesDownloaded - bytesDownloadedSinceLastQuery);
    
            bytesDownloadedSinceLastQuery = downloader.bytesDownloaded; // CHANGE
        }
    
    //and in the other file
    
    public FTPDownloadFile()
    {
        bytesDownloaded = 0;
        Speed = new SpeedCalculator( this ); // CHANGE
    }
    

    In C#, every object (class MyObject) is passed by reference, or implicit pointer, therefore taking FTPDownloadFile by parameter and assigning it to a member variable does not copy it, it is truly passed by ref (on the other hand, values (int, decimal, ..) and structs (struct MyThing) are always passed by value, so your original _bytes = bytes made a copy of int). Hence, later, I can just query the

    Ex#2: “weak” reference

    public interface IByteCountSource
    {
        int BytesDownloaded {get;}
    }
    
    public class FTPDownloadFile : IDisposable, IByteCountSource
    {
        .....
        public int BytesDownloaded { get { return bytesDownloaded; } }
        .....
    
        public FTPDownloadFile()
        {
           bytesDownloaded = 0;
           Speed = new SpeedCalculator( this ); // note no change versus Ex#1 !
        }
    }
    
    public class SpeedCalculator
    {
        ....
    
        private IByteCountSource bts;
    
        public SpeedCalculator(IByteCountSource countSource) // no "FTP" information!
        {
            this.bts = countSource;
        }
    
        ...
    
        private void QueryByteDelta(object data)
        {
            ....
    
            bytesDownloadedSinceLastQuery = bts.BytesDownloaded;
        }
    

    The first example was quick and dirty. In general, we usually want the classes to know as least as possible about all other. So why should the SpeedCalculator know about the FTPDownloadFile? All it needs to know is the current byte-count. So I introduced an interface to ‘hide’ the actual source behind. Now the SpeedCalculator can take the value from any object that implements the interface – be it FTPDownloadFile, HTTPDownloadFile or some DummyTestDownloader

    Ex#3: delegates, anonymous functions, etc

    public class SpeedCalculator
    {
        ....
    
        private Func<int> bts;
    
        public SpeedCalculator(Func<int> countSource)
        {
            this.bts = countSource;
        }
    
        ...
    
        private void QueryByteDelta(object data)
        {
            ....
    
            bytesDownloadedSinceLastQuery = bts();
        }
    
    // and in the other file
    
    private int getbytes() { return bytesDownloaded; }
    
    public FTPDownloadFile()
    {
        bytesDownloaded = 0;
        Speed = new SpeedCalculator( this.getbytes ); // note it is NOT a getbytes() !
    }
    
    // or even
    
    public FTPDownloadFile()
    {
        bytesDownloaded = 0;
        Speed = new SpeedCalculator( () => this.bytesDownloaded ); // CHANGE
    }
    

    The example with an interface is pretty, but the interface was ‘small’. One is ok, but sometimes you’d need to introduce dozens of such one-property or one-method interfaces, it gets somewhat boring and cluttering. Especially if all of that is ‘internal implementation’ that anyways isn’t published for any other people to use. You can very easily drop such small interface with a short lambda, as in the third example. Instead of receiving and storing a object-that-implememts-an-interface, I changed the parameter to Func. This way I require to get “a method that returns an INT”. Them, I pass the some method. Note that during new SpeedCalculator, I do not call the this.getbytes(), I pass the method without parenthesis – this causes the method to be wrapped into Func delegate, that will be later invoked as bts(), and will return current counter. This getbytes is rarely used, only in this one place – so I can even drop it completely and write anonymous function right at the point of constructor call, as you can see in the “or even” part.

    However, I’d suggest you to stick with interfaces for now, they are much clearer to read and understand.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want use html5's new tag to play a wav file (currently only supported
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I am writing an app with both english and french support. The app requests
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I am currently running into a problem where an element is coming back from
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am writing an app for my school newspaper, which is run completely online

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.