我正在编写网络下载器并遇到了奇怪的问题。示例代码:
int chunk;
var request = WebRequest.Create(uri) as HttpWebRequest;
using (WebResponse response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (Stream file = File.Create(filePath))
{
long byteReaded = 0;
long contentLength = response.ContentLength;
while (byteReaded < contentLength)
{
long bytesCountToRead = contentLength - byteReaded > chunk ? chunk : contentLength - byteReaded;
byte[] buffer = new byte[bytesCountToRead];
responseStream.Read(buffer, 0, buffer.Length);
file.Write(buffer, 0, buffer.Length);
byteReaded += bytesCountToRead;
}
}
}
}
问题:当 'chunk' 变量 == 1 或 2 字节时没关系。但是当这个尺寸更大时 - 图像会受到干扰!我发现它与下载速度(响应阅读速度)有关,因为当我设置更大的尺寸并在循环的最后一行chunk
插入时,图像保持正常。希望有人可以帮助我。Thread.Sleep(time)
while