【发布时间】:2016-09-26 07:18:28
【问题描述】:
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();
}
}
【问题讨论】:
-
你是怎么调用这个方法的,你可能阻塞了同步上下文,所以阻塞是真实的。还有
voidreturn big no,请回复Task -
如何让它正确返回一个任务?
-
请详细说明,不确定您的意思是如何将返回的任务正确映射到调用者。这里
Task(非泛型)没有返回值,是对void的更好替代,尤其是在Async方法中有异常时
标签: c# events asynchronous delegates async-await