Skip to content

Instantly share code, notes, and snippets.

@kflu
Last active February 22, 2018 08:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kflu/402af56c98029afd3e8825364872980c to your computer and use it in GitHub Desktop.
Save kflu/402af56c98029afd3e8825364872980c to your computer and use it in GitHub Desktop.
How to throttle upload speed using progress handler
/*
* RateThrottleProgress.cs
* Copyright (C) 2018 Kefei Lu
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Usage with Azure Storage SDK:
*
* await blob.UploadFromFileAsync(
* @"some_file.dat",
* null, null, null,
* new RateThrottleProgress(300 * 1024), // throttle at 300kb/s
* CancellationToken.None);
* See my StackOverflow answer here: https://stackoverflow.com/a/48922875/695964
*/
class RateThrottleProgress : IProgress<StorageProgress>
{
private readonly DateTime start = DateTime.Now;
private readonly long maxbps;
private long baseDelay, delay;
public RateThrottleProgress(long maxbps)
{
this.maxbps = maxbps;
baseDelay = 10;
delay = baseDelay;
}
public void Report(StorageProgress value)
{
double duration = (DateTime.Now - start).TotalSeconds;
double bps = value.BytesTransferred / duration;
if (bps > maxbps) delay *= 2;
else delay = Math.Max(baseDelay, delay/2);
Console.WriteLine($"current estimated upload speed: {bps / 1024.0} KB/s. delay: {delay} ms");
Thread.Sleep(TimeSpan.FromMilliseconds(delay));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment