I'm writing a utility that will be uploading a bunch of files, and would like to provide the option to rate limit uploads. What is the best approach for rate limiting uploads when using the TcpClient class? My first instinct is to call NetworkStream.Write() with a limited number of bytes at a time, sleeping between calls (and skipping a call if the stream isn't done writing yet) until the buffer is uploaded. Has anyone implemented something like this before?
Implementing speed limit is relatively easy, take a look at the following snippet:
const int OneSecond = 1000;
int SpeedLimit = 1024; // Speed limit 1kib/s
int Transmitted = 0;
Stopwatch Watch = new Stopwatch();
Watch.Start();
while(...)
{
// Your send logic, which return BytesTransmitted
Transmitted += BytesTransmitted;
// Check moment speed every five second, you can choose any value
int Elapsed = (int)Watch.ElapsedMilliseconds;
if (Elapsed > 5000)
{
int ExpectedTransmit = SpeedLimit * Elapsed / OneSecond;
int TransmitDelta = Transmitted - ExpectedTransmit;
// Speed limit exceeded, put thread into sleep
if (TransmitDelta > 0)
Thread.Wait(TransmitDelta * OneSecond / SpeedLimit);
Transmitted = 0;
Watch.Reset();
}
}
Watch.Stop();
This is draft untested code, but I think it is enough to get the main idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With