Click here to Skip to main content
15,501,148 members
Articles / Web Development / ASP.NET
Posted 2 Apr 2007


139 bookmarked

Bandwidth throttling

Rate me:
Please Sign up or sign in to vote.
4.75/5 (59 votes)
2 Apr 2007CPOL2 min read
Save bandwidth and get QoS with bandwidth throttling.

Screenshot - screen.jpg


Hosting a website can be fun. But, when you offer big downloads or streaming media, you do not want a visitor to eat up the full bandwidth. Or, maybe, you want to offer a premium account from where users can download without limitation, and a free account where users cannot download faster than 50 kb/s. Here is where throttling comes in.

Bandwidth throttling helps provide quality of service (QoS) by limiting network congestion and server crashes. For example, you make sure a connection does not get more than an X number of bytes per second.

The purpose of this article is to show how to use bandwidth throttling, with a small helper class.

Using the code

Within the source code, you will find a class named ThrottledStream. This class is derived from the abstract Stream that can be found in the System.IO namespace. In the constructor, it accepts a base stream to throttle. Here is a small line of code that shows how to instantiate a ThrottledStream:

Stream throttledStream = new ThrottledStream(Response.OutputStream, 1024);

Now, everything you do with the throttledStream will be limited to 1024 bytes per second, and will be send to or read from the OutputStream that is a member of the Response property that exists within an ASP.NET page.

Because the ThrottledStream is derived from the abstract Stream class, it is easy to add throttling to an existing application or website. For example, when you have a process that sends file content over a Stream and you want to enable bandwidth throttling, you only have to change the initialization of the destination stream.

The old code can look like this:

Stream sourceStream;
Stream destinationStream;

    sourceStream = new FileStream(@"c:\myfile.bin", 
                       FileMode.Open, FileAccess.Read, FileShare.Read);
    destinationStream = new NetworkStream(mySocket, false);

    byte[] buffer = new byte[1024];
    int readCount = sourceStream.Read(buffer, 0, BufferSize);

    while (readCount > 0)
        destinationStream.Write(buffer, 0, readCount);
        readCount = sourceStream.Read(buffer, 0, BufferSize);
    if (destinationStream != null)
    if (sourceStream != null)

Now, we can easily add throttling support to this process. We only need to change the initialization:


Stream originalDestinationStream = new NetworkStream(mySocket, false);
destinationStream = new ThrottledStream(originalDestinationStream, 51200);


By adding only one line of code, this full process is throttled to 50 kb/s (51200 b/s). Now, we go even a step further and add throttling that is based on a membership:


long bps;

switch( user.Membership )
    case MembershipLevel.Bronze:
        bps = 51200;

    case MembershipLevel.Silver:
        bps = 102400;

    case MembershipLevel.Gold:
        bps = 153600;

    case MembershipLevel.Platina:
        bps = ThrottledStream.Infinite;

Stream originalDestinationStream = new NetworkStream(mySocket, false);
destinationStream = new ThrottledStream(originalDestinationStream, bps);


Here, we have a situation where a Bronze membership will give you 50 kb/s, Silver 100 kb/s, Gold 150 kb/s, and Platina infinitive - no throttling.

Points of interest

Bandwidth throttling can improve the QoS of your server, and allows you to control the bandwidth for a specified connection. The helper class named ThrottledStream is very easy to use, and can be used in existing scenarios.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Architect Sogyo
Netherlands Netherlands
Pieter Joost is a sr. IT consultant at Sogyo. He is recently awarded as Microsoft Visual C# MVP. He's active in the software development community as a speaker and boardmember of and

Comments and Discussions

QuestionWhy inherit from Stream? Pin
copa01730-Nov-18 3:57
Membercopa01730-Nov-18 3:57 
QuestionWorking but sometimes its showing more speed Pin
Member 116092747-Sep-17 21:43
MemberMember 116092747-Sep-17 21:43 
GeneralRe: Working but sometimes its showing more speed Pin
Muhammad Owais4-Oct-21 22:37
MemberMuhammad Owais4-Oct-21 22:37 
QuestionHow to configure it using VS2015 Windows 10. Pin
Member 1291430020-Dec-16 6:29
MemberMember 1291430020-Dec-16 6:29 
QuestionUnderstanding the bandwith usage Pin
gemese24-Apr-16 0:45
Membergemese24-Apr-16 0:45 
I'm trying to understand the bandwidth usage from the class's example, but i never reach more than the 50% of my 1gb network.

I'm transferring files that the size is between 100Gb and 200gb, and also at the worst situation, transferring from a remote machine to another remote machine.

I use the ThrottledStream(DestinyStream, bps); with zero bps and the buffer-size with many different numbers. I had been trying, between 8bytes, 256bytes, 8kb(8192),80kb(81920) and at the end using a function to get all the available free memory to get the max buffer-size possible.

But this had ended in a 0.1% usage of the network. Dead | X|

This is my function to use the ThrottledStream.

public bool fnGlobFCopyBandwidthWithProgress(string strSourceFileName, string strDesntinyFileName, int BufferSize, long bps, out string strResult)
        FileInfo file = new FileInfo(strSourceFileName);

        if (!file.Exists)
            throw new DirectoryNotFoundException("Source file does not exist or could not be found: " + strSourceFileName);
            //return false;

           using (FileStream sourceStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))

                //Get the total size of the download
                Int64 dataLength = sourceStream.Length;

                //To control the progress for the transfer.
                ByteArgs byteArgs = new ByteArgs();
                byteArgs.downloaded = 0;
       = file.Length;
                byteArgs.FileName = strDesntinyFileName;

                //we need to test for a null as if an event is not consumed we will get an exception
                if (bytesDownloaded != null) bytesDownloaded(byteArgs);

                using (FileStream DestinyStream = new FileStream(strDesntinyFileName, FileMode.Create, FileAccess.Write, FileShare.Write))

                    // Create throttled destination stream.
                    ThrottledStream destinationStream = new ThrottledStream(DestinyStream, bps);

                    byte[] buffer = new byte[BufferSize];
                    int readCount = sourceStream.Read(buffer, 0, BufferSize);

                    while (readCount > 0)
                        destinationStream.Write(buffer, 0, readCount);
                        readCount = sourceStream.Read(buffer, 0, BufferSize);

                        //To control the progress for the transfer.
                        byteArgs.downloaded += readCount;
               = dataLength;
                        if (bytesDownloaded != null) bytesDownloaded(byteArgs);

    catch (Exception Ex)
        strResult = "Error: InnerException: " + Ex.InnerException + "#Message: " + Ex.Message + "#Source: " + Ex.Source + "#StackTrace: " + Ex.StackTrace;
        return false;

    strResult = "";
    return true;

and the call:

        private const int KILOBYTE = 1024;
        private const int MEGABYTE = 1024*1024;
        private const int BufferSize_256b = 256;
        private const int BufferSize_8kb = 8192;
        private const int BufferSize_4kb = 4096;
        private const int BufferSize_80kb = 81920;

int intBuffSize = BufferSize_8kb;

if (bpsRemote == 0)
    bpsRemote = ThrottledStream.Infinite;
    //intBuffSize = MEGABYTE;
    //intBuffSize = BufferSize_256b;
    //intBuffSize = BufferSize_8kb;
    //intBuffSize = BufferSize_4kb;
    //intBuffSize = BufferSize_80kb;
    //intBuffSize = (int)objComputer.GetMemoryInMiB("total") * KILOBYTE; //Will crash.
    intBuffSize = (int)objComputer.GetMemoryInMiB("Available") * KILOBYTE;

bolFileCopied = objGlobalFiles.fnGlobFCopyBandwidthWithProgress(KeyOrigin.ToString(), strNewPathDestiny.ToString(), intBuffSize, bpsRemote, out strResultado);

I will continue trying with different approaches.

Maybe, this class is not intended for a file transfer over lan network and control the bandwidth... but i spent useful hours and it doesn't matter... Thanks a lot, for ThrottledStream class and the example!

I will learn how to use the windows shadow copy and try to use other approaches to wrap the "FileSystem.CopyTo()" function.
QuestionUpdated Sourcecode Pin
sx200823-Jul-15 2:20
Membersx200823-Jul-15 2:20 
AnswerRe: Updated Sourcecode Pin
Meixger Martin22-Jan-16 1:16
MemberMeixger Martin22-Jan-16 1:16 
AnswerRe: Updated Sourcecode Pin
jerry_wangjh4-Feb-18 22:21
Memberjerry_wangjh4-Feb-18 22:21 
QuestionBandwidth throttling in Task-based async methods? Pin
Alex Zelid2-Apr-14 3:54
MemberAlex Zelid2-Apr-14 3:54 
QuestionMy vote of 5 Pin
AndyInPembs12-Dec-12 1:00
MemberAndyInPembs12-Dec-12 1:00 
Questioncreate socket Pin
Arash Zeinoddini21-Aug-12 12:44
MemberArash Zeinoddini21-Aug-12 12:44 
Questionupload throttled Pin
nandobv10-Mar-12 16:10
Membernandobv10-Mar-12 16:10 
Generalhow to use ThrottledStream class Pin
as206em19-May-11 6:28
Memberas206em19-May-11 6:28 
QuestionHow throttle each connection TCP/UDP? Pin
egcf21-Nov-10 12:15
Memberegcf21-Nov-10 12:15 
GeneralProblems Pin
NN---21-Sep-10 3:15
MemberNN---21-Sep-10 3:15 
GeneralBandwidth throttling Pin
commenter210-Mar-10 12:07
Membercommenter210-Mar-10 12:07 
QuestionWhat with worker threadpool ? Pin
neoandrew7-Mar-10 15:10
Memberneoandrew7-Mar-10 15:10 
GeneralThanks ! Pin
Ahmed Charfeddine1-Jun-09 2:17
MemberAhmed Charfeddine1-Jun-09 2:17 
GeneralIt works! Pin
dimpant8-May-09 15:41
Memberdimpant8-May-09 15:41 
GeneralRe: It works! Pin
dimpant16-May-09 0:09
Memberdimpant16-May-09 0:09 
GeneralRe: It works! Pin
Goran___20-Aug-09 3:54
MemberGoran___20-Aug-09 3:54 
QuestionCan I adjust the bit rate on the fly? Pin
ebonnett29-Apr-09 7:22
Memberebonnett29-Apr-09 7:22 
AnswerRe: Can I adjust the bit rate on the fly? Pin
st0icsmitty15-Dec-09 11:25
Memberst0icsmitty15-Dec-09 11:25 
GeneralRe: Can I adjust the bit rate on the fly? Yes... [modified] Pin
thomastmc5-Feb-10 5:04
Memberthomastmc5-Feb-10 5:04 
GeneralIdle for a while after creating ThrottledStream constructor Pin
SchoonMan14-Oct-08 9:07
MemberSchoonMan14-Oct-08 9:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.