Advertisement
ivandrofly

Throttle Stream

Jun 24th, 2024
634
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.07 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Diagnostics;
  5.  
  6. namespace Born2Code.Net
  7. {
  8.     /// <summary>
  9.     /// Class for streaming data with throttling support.
  10.     /// </summary>
  11.     public class ThrottledStream : Stream
  12.     {
  13.         /// <summary>
  14.         /// A constant used to specify an infinite number of bytes that can be transferred per second.
  15.         /// </summary>
  16.         public const long Infinite = 0;
  17.  
  18.         #region Private members
  19.         /// <summary>
  20.         /// The base stream.
  21.         /// </summary>
  22.         private Stream _baseStream;
  23.  
  24.         /// <summary>
  25.         /// The maximum bytes per second that can be transferred through the base stream.
  26.         /// </summary>
  27.         private long _maximumBytesPerSecond;
  28.  
  29.         /// <summary>
  30.         /// The number of bytes that has been transferred since the last throttle.
  31.         /// </summary>
  32.         private long _byteCount;
  33.  
  34.         /// <summary>
  35.         /// The start time in milliseconds of the last throttle.
  36.         /// </summary>
  37.         private long _start;
  38.         #endregion
  39.  
  40.         #region Properties
  41.         /// <summary>
  42.         /// Gets the current milliseconds.
  43.         /// </summary>
  44.         /// <value>The current milliseconds.</value>
  45.         protected long CurrentMilliseconds
  46.         {
  47.             get
  48.             {
  49.                 return Environment.TickCount;
  50.             }
  51.         }
  52.  
  53.         /// <summary>
  54.         /// Gets or sets the maximum bytes per second that can be transferred through the base stream.
  55.         /// </summary>
  56.         /// <value>The maximum bytes per second.</value>
  57.         public long MaximumBytesPerSecond
  58.         {
  59.             get
  60.             {
  61.                 return _maximumBytesPerSecond;
  62.             }
  63.             set
  64.             {
  65.                 if (MaximumBytesPerSecond != value)
  66.                 {
  67.                     _maximumBytesPerSecond = value;
  68.                     Reset();
  69.                 }
  70.             }
  71.         }
  72.  
  73.         /// <summary>
  74.         /// Gets a value indicating whether the current stream supports reading.
  75.         /// </summary>
  76.         /// <returns>true if the stream supports reading; otherwise, false.</returns>
  77.         public override bool CanRead
  78.         {
  79.             get
  80.             {
  81.                 return _baseStream.CanRead;
  82.             }
  83.         }
  84.  
  85.         /// <summary>
  86.         /// Gets a value indicating whether the current stream supports seeking.
  87.         /// </summary>
  88.         /// <value></value>
  89.         /// <returns>true if the stream supports seeking; otherwise, false.</returns>
  90.         public override bool CanSeek
  91.         {
  92.             get
  93.             {
  94.                 return _baseStream.CanSeek;
  95.             }
  96.         }
  97.  
  98.         /// <summary>
  99.         /// Gets a value indicating whether the current stream supports writing.
  100.         /// </summary>
  101.         /// <value></value>
  102.         /// <returns>true if the stream supports writing; otherwise, false.</returns>
  103.         public override bool CanWrite
  104.         {
  105.             get
  106.             {
  107.                 return _baseStream.CanWrite;
  108.             }
  109.         }
  110.  
  111.         /// <summary>
  112.         /// Gets the length in bytes of the stream.
  113.         /// </summary>
  114.         /// <value></value>
  115.         /// <returns>A long value representing the length of the stream in bytes.</returns>
  116.         /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking. </exception>
  117.         /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  118.         public override long Length
  119.         {
  120.             get
  121.             {
  122.                 return _baseStream.Length;
  123.             }
  124.         }
  125.  
  126.         /// <summary>
  127.         /// Gets or sets the position within the current stream.
  128.         /// </summary>
  129.         /// <value></value>
  130.         /// <returns>The current position within the stream.</returns>
  131.         /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  132.         /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking. </exception>
  133.         /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  134.         public override long Position
  135.         {
  136.             get
  137.             {
  138.                 return _baseStream.Position;
  139.             }
  140.             set
  141.             {
  142.                 _baseStream.Position = value;
  143.             }
  144.         }
  145.         #endregion
  146.  
  147.         #region Ctor
  148.         /// <summary>
  149.         /// Initializes a new instance of the <see cref="T:ThrottledStream"/> class with an
  150.         /// infinite amount of bytes that can be processed.
  151.         /// </summary>
  152.         /// <param name="baseStream">The base stream.</param>
  153.         public ThrottledStream(Stream baseStream)
  154.             : this(baseStream, ThrottledStream.Infinite)
  155.         {
  156.             // Nothing todo.
  157.         }
  158.  
  159.         /// <summary>
  160.         /// Initializes a new instance of the <see cref="T:ThrottledStream"/> class.
  161.         /// </summary>
  162.         /// <param name="baseStream">The base stream.</param>
  163.         /// <param name="maximumBytesPerSecond">The maximum bytes per second that can be transferred through the base stream.</param>
  164.         /// <exception cref="ArgumentNullException">Thrown when <see cref="baseStream"/> is a null reference.</exception>
  165.         /// <exception cref="ArgumentOutOfRangeException">Thrown when <see cref="maximumBytesPerSecond"/> is a negative value.</exception>
  166.         public ThrottledStream(Stream baseStream, long maximumBytesPerSecond)
  167.         {
  168.             if (baseStream == null)
  169.             {
  170.                 throw new ArgumentNullException("baseStream");
  171.             }
  172.  
  173.             if (maximumBytesPerSecond < 0)
  174.             {
  175.                 throw new ArgumentOutOfRangeException("maximumBytesPerSecond",
  176.                     maximumBytesPerSecond, "The maximum number of bytes per second can't be negatie.");
  177.             }
  178.  
  179.             _baseStream = baseStream;
  180.             _maximumBytesPerSecond = maximumBytesPerSecond;
  181.             _start = CurrentMilliseconds;
  182.             _byteCount = 0;
  183.         }
  184.         #endregion
  185.  
  186.         #region Public methods
  187.         /// <summary>
  188.         /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
  189.         /// </summary>
  190.         /// <exception cref="T:System.IO.IOException">An I/O error occurs.</exception>
  191.         public override void Flush()
  192.         {
  193.             _baseStream.Flush();
  194.         }
  195.  
  196.         /// <summary>
  197.         /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
  198.         /// </summary>
  199.         /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
  200.         /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
  201.         /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  202.         /// <returns>
  203.         /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
  204.         /// </returns>
  205.         /// <exception cref="T:System.ArgumentException">The sum of offset and count is larger than the buffer length. </exception>
  206.         /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  207.         /// <exception cref="T:System.NotSupportedException">The base stream does not support reading. </exception>
  208.         /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
  209.         /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  210.         /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
  211.         public override int Read(byte[] buffer, int offset, int count)
  212.         {
  213.             Throttle(count);
  214.  
  215.             return _baseStream.Read(buffer, offset, count);
  216.         }
  217.  
  218.         /// <summary>
  219.         /// Sets the position within the current stream.
  220.         /// </summary>
  221.         /// <param name="offset">A byte offset relative to the origin parameter.</param>
  222.         /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"></see> indicating the reference point used to obtain the new position.</param>
  223.         /// <returns>
  224.         /// The new position within the current stream.
  225.         /// </returns>
  226.         /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  227.         /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
  228.         /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  229.         public override long Seek(long offset, SeekOrigin origin)
  230.         {
  231.             return _baseStream.Seek(offset, origin);
  232.         }
  233.  
  234.         /// <summary>
  235.         /// Sets the length of the current stream.
  236.         /// </summary>
  237.         /// <param name="value">The desired length of the current stream in bytes.</param>
  238.         /// <exception cref="T:System.NotSupportedException">The base stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception>
  239.         /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  240.         /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  241.         public override void SetLength(long value)
  242.         {
  243.             _baseStream.SetLength(value);
  244.         }
  245.  
  246.         /// <summary>
  247.         /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  248.         /// </summary>
  249.         /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
  250.         /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
  251.         /// <param name="count">The number of bytes to be written to the current stream.</param>
  252.         /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  253.         /// <exception cref="T:System.NotSupportedException">The base stream does not support writing. </exception>
  254.         /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  255.         /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
  256.         /// <exception cref="T:System.ArgumentException">The sum of offset and count is greater than the buffer length. </exception>
  257.         /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
  258.         public override void Write(byte[] buffer, int offset, int count)
  259.         {
  260.             Throttle(count);
  261.  
  262.             _baseStream.Write(buffer, offset, count);
  263.         }
  264.  
  265.         /// <summary>
  266.         /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
  267.         /// </summary>
  268.         /// <returns>
  269.         /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
  270.         /// </returns>
  271.         public override string ToString()
  272.         {
  273.             return _baseStream.ToString();
  274.         }
  275.         #endregion
  276.  
  277.         #region Protected methods
  278.         /// <summary>
  279.         /// Throttles for the specified buffer size in bytes.
  280.         /// </summary>
  281.         /// <param name="bufferSizeInBytes">The buffer size in bytes.</param>
  282.         protected void Throttle(int bufferSizeInBytes)
  283.         {
  284.             // Make sure the buffer isn't empty.
  285.             if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0)
  286.             {
  287.                 return;
  288.             }
  289.  
  290.             _byteCount += bufferSizeInBytes;
  291.             long elapsedMilliseconds = CurrentMilliseconds - _start;
  292.  
  293.             if (elapsedMilliseconds > 0)
  294.             {
  295.                 // Calculate the current bps.
  296.                 long bps = _byteCount * 1000L / elapsedMilliseconds;
  297.  
  298.                 // If the bps are more then the maximum bps, try to throttle.
  299.                 if (bps > _maximumBytesPerSecond)
  300.                 {
  301.                     // Calculate the time to sleep.
  302.                     long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
  303.                     int toSleep = (int)(wakeElapsed - elapsedMilliseconds);
  304.  
  305.                     if (toSleep > 1)
  306.                     {
  307.                         try
  308.                         {
  309.                             // The time to sleep is more then a millisecond, so sleep.
  310.                             Thread.Sleep(toSleep);
  311.                         }
  312.                         catch (ThreadAbortException)
  313.                         {
  314.                             // Eatup ThreadAbortException.
  315.                         }
  316.  
  317.                         // A sleep has been done, reset.
  318.                         Reset();
  319.                     }
  320.                 }
  321.             }
  322.         }
  323.  
  324.         /// <summary>
  325.         /// Will reset the bytecount to 0 and reset the start time to the current time.
  326.         /// </summary>
  327.         protected void Reset()
  328.         {
  329.             long difference = CurrentMilliseconds - _start;
  330.  
  331.             // Only reset counters when a known history is available of more then 1 second.
  332.             if (difference > 1000)
  333.             {
  334.                 _byteCount = 0;
  335.                 _start = CurrentMilliseconds;
  336.             }
  337.         }
  338.         #endregion
  339.     }
  340. }
  341.  
  342. Source: Born2Code.Net (Throttling)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement