Пример #1
0
        internal static async Task <bool> WaitForDownloadResult(IBaseDownloader downloader)
        {
            var success = false;
            var cs      = new CancellationTokenSource();

            downloader.Finished += (a, b) =>
            {
                success = true;
                cs.Cancel();
            };
            downloader.Failed += (a, b) =>
            {
                success = false;
                cs.Cancel();
            };

            downloader.Start();

            try
            {
                await Task.Delay(Int32.MaxValue, cs.Token);
            }
            catch { }

            return(success);
        }
Пример #2
0
        public void ThrottleIfNeeded(IBaseDownloader downloader)
        {
            int speedLimit = GetCachedSpeedLimit();

            if (speedLimit < 1)
            {
                return;
            }
            if (lastBytes == 0 || lastTick == 0)
            {
                lastBytes = downloader.GetDownloaded();
                lastTick  = Helpers.TickCount();
                return;
            }
            try
            {
                downloader.Lock.EnterWriteLock();
                var maxBytesPerMS   = (double)speedLimit * 1024 / 1000;
                var now             = Helpers.TickCount();
                var actualTimeSpent = now - lastTick;
                if (actualTimeSpent < 1)
                {
                    return;
                }
                var bytes = downloader.GetDownloaded();
                var diff  = bytes - lastBytes;
                lastBytes = bytes;
                lastTick  = now;
                var expectedTimeSpent = diff / maxBytesPerMS;

                if (actualTimeSpent < expectedTimeSpent)
                {
                    try
                    {
                        sleep((int)Math.Ceiling(expectedTimeSpent - actualTimeSpent));
                    }
                    catch (Exception ex) { Log.Debug(ex, "Exception while throttling"); }
                }
            }
            finally
            {
                downloader.Lock.ExitWriteLock();
            }
        }