XG.Plugin.Irc.ThrottledStream.Throttle C# (CSharp) Method

Throttle() protected method

protected Throttle ( int bufferSizeInBytes ) : void
bufferSizeInBytes int
return void
        protected void Throttle(int bufferSizeInBytes)
        {
            if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0)
            {
                return;
            }

            _byteCount += bufferSizeInBytes;
            long elapsedMilliseconds = CurrentMilliseconds - _start;

            if (elapsedMilliseconds > 0)
            {
                // Calculate the current bps.
                long bps = _byteCount * 1000L / elapsedMilliseconds;

                // If the bps are more then the maximum bps, try to throttle.
                if (bps > _maximumBytesPerSecond)
                {
                    // Calculate the time to sleep.
                    long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
                    int toSleep = (int)(wakeElapsed - elapsedMilliseconds);

                    if (toSleep > 1)
                    {
                        try
                        {
                            Thread.Sleep(toSleep);
                        }
                        catch (ThreadAbortException) {}
                        finally
                        {
                            Reset();
                        }
                    }
                }
            }
        }