0 c# events delegates asynchronous async-await
static async void DownloadData(TextBox textboxURL, TextBlock outputView)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(textboxURL.Text);
client.Timeout = TimeSpan.FromMinutes(1);
var request = new HttpRequestMessage(HttpMethod.Get, textboxURL.Text);
/// Fixed thanks to: http://stackoverflow.com/questions/18720435/httpclient-buffer-size-limit-exceeded
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
/// Version = response.Version.ToString();
response.EnsureSuccessStatusCode();
// Result = await response.Content.ReadAsStringAsync();
// Task<Stream> inputStream = response.Content.ReadAsStreamAsync();
/// DUPE CODE: var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
/// NEED TO READ UP ON THIS: response..Result.EnsureSuccessStatusCode();
var httpStream = await response.Content.ReadAsStreamAsync();
var picker = new FileSavePicker()
{
SuggestedStartLocation = PickerLocationId.Downloads,
SuggestedFileName = "DOWNLOADING.BIN"
};
picker.FileTypeChoices.Add("Any", new List<string>() { "." });
/// picker.FileTypeChoices.Add("Any", new List<string>() { "*" });
StorageFile storageFile = await picker.PickSaveFileAsync();
// Woohoo! Got it working using await, and removing the Task<> wrapper!
using (var reader = new StreamReader(httpStream))
{
Stream fileStream = await storageFile.OpenStreamForWriteAsync();
httpStream.CopyTo(fileStream);
fileStream.Flush();
}
}
}
catch (Exception ex)
{
outputView.Text = "Error, try again!";
var dlg = new Windows.UI.Popups.MessageDialog(ex.Message, "Error");
await dlg.ShowAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
你在Stream.CopyTo这里使用同步方法:
httpStream.CopyTo(fileStream);
Run Code Online (Sandbox Code Playgroud)
我想你只想要:
await httpStream.CopyToAsync(fileStream);
Run Code Online (Sandbox Code Playgroud)
但是,您还应该删除该StreamReader部分 - 您没有使用它StreamReader,并且它可能会尝试读取一些数据来检测编码.但是,您应该使用using存储文件的语句.所以基本上,改变这个:
using (var reader = new StreamReader(httpStream))
{
Stream fileStream = await storageFile.OpenStreamForWriteAsync();
httpStream.CopyTo(fileStream);
fileStream.Flush();
}
Run Code Online (Sandbox Code Playgroud)
至:
using (Stream fileStream = await storageFile.OpenStreamForWriteAsync())
{
await httpStream.CopyToAsync(fileStream);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |