This question already has an answer here:
I need to implement a download rate limit for my file downloader application, and I've looked at the ThrottledStream
class from CodeProject, but this won't work in my case since I have to be able to change the limit during a download, not just at the beginning. Here's a part of the download method that I'm using in a background thread:
webResponse = (HttpWebResponse)webRequest.GetResponse();
responseStream = webResponse.GetResponseStream();
responseStream.ReadTimeout = 5000;
downloadCache = new MemoryStream(this.MaxCacheSize);
byte[] downloadBuffer = new byte[this.BufferSize];
int bytesSize = 0;
CachedSize = 0;
int receivedBufferCount = 0;
while (true)
{
bytesSize = responseStream.Read(downloadBuffer, 0, downloadBuffer.Length);
if (this.Status != DownloadStatus.Downloading || bytesSize == 0
|| this.MaxCacheSize < CachedSize + bytesSize)
{
WriteCacheToFile(downloadCache, CachedSize);
this.DownloadedSize += CachedSize;
downloadCache.Seek(0, SeekOrigin.Begin);
CachedSize = 0;
if (this.Status != DownloadStatus.Downloading || bytesSize == 0)
break;
}
downloadCache.Write(downloadBuffer, 0, bytesSize);
CachedSize += bytesSize;
receivedBufferCount++;
if (receivedBufferCount == this.BufferCountPerNotification)
{
this.RaiseDownloadProgressChanged();
receivedBufferCount = 0;
}
}
I've also seen people using Thread.Sleep() or Thread.Wait(), but is it a good idea? Do you have any suggestions how I could do this inside this while loop?
I have used this code to download files from the server may be it is helpful to you...