【发布时间】:2014-04-17 13:22:32
【问题描述】:
我面临一个奇怪的问题,我必须承认 - 不明白。我有一个任务,它正在从 Web 异步下载文件:
public async Task DownloadFile(Uri requestUri, string fileName, IProgress<int> progress)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(requestUri);
request.Method = "GET";
request.AllowReadStreamBuffering = false;
using (WebResponse response = await request.GetResponseAsync())
using (Stream mystr = response.GetResponseStream())
{
StorageFolder local = ApplicationData.Current.LocalFolder;
StorageFile file = await local.CreateFileAsync(fileName);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
const int BUFFER_SIZE = 100 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread = 0;
// the problem is here below
while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
await fileStream.WriteAsync(buf, 0, bytesread);
progress.Report(bytesread);
}
}
}
}
任务正在运行,但正如您所见,它应该报告其进度。
事实证明,问题出在程序到达bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE) 行时——在整个文件下载完成之前,它不会对该线程执行任何其他操作(不仅是BUFFER_SIZE)。完成下载后,while 循环会被触发多次,并从内存中复制流——速度非常快。
奇怪的是,相同的代码在 WP8.0 上运行没有问题,现在我尝试在 WP8.1 上运行它,我遇到了这个问题。有人知道我做错了什么吗?
【问题讨论】:
标签: c# windows-phone-8 asynchronous async-await windows-phone-8.1