对不起,如果之前已经回答过这个问题,但没有一个答案对我有帮助。我的WebView有一个事件:
private async void MainWebView_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
{
await downloadFromUri(args.Uri).ConfigureAwait(false);
}
我的downloadFromUri方法将尝试下载文件并将其存储在downloads文件夹中,最后它将打开文件:
static async Task downloadFromUri(Uri uri)
{
var url = uri;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAppendWithoutValidation(
"Authorization Bearer",
" MYTOKEN"
);
Debug.WriteLine("Attempting GET request");
var response = await client.GetAsync(url);
Debug.WriteLine("Got response.. checking " + response.StatusCode);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine("Okay, we've got a response");
var responseFileName = response.Content.Headers.ContentDisposition.FileName;
Debug.WriteLine("Filename: " + responseFileName);
var ManualFile = await DownloadsFolder.CreateFileAsync(responseFileName, CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Creating buffer: ");
var buffer = await client.GetBufferAsync(url);
Debug.WriteLine("Writing buffer.");
await Windows.Storage.FileIO.WriteBufferAsync(ManualFile, buffer);
Debug.WriteLine("Done, opening");
var openOptions = new Windows.System.LauncherOptions();
openOptions.DisplayApplicationPicker = true;
var openFile = await Windows.System.Launcher.LaunchFileAsync(ManualFile, openOptions);
}
else
{
Debug.WriteLine(response.StatusCode.ToString());
}
}
问题是,这个代码似乎可以在小PDF或zip文件上正常工作。但是当涉及到>的PDF文件时10mb,应用程序挂起在以下行:
var response = await client.GetAsync(url);
我可以做些什么来完成这项工作?非常感谢提前!
注意:我使用的是Windows.Web.Http.HttpClient,而不是System.Net.Http.HttpClient。
修改:我已尝试跳过client.GetAsync(url)
并直接运行var buffer = await client.GetBufferAsync(url);
。这也会挂起。
答案 0 :(得分:3)
对于较大的文件,最好使用
Windows.Networking.BackgroundTransfer
命名空间,如BackgroundDownloader
?
答案 1 :(得分:2)
请将您的代码更改为 -
var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false));
另请参阅此 - HttpClient.GetAsync(...) never returns when using await/async
或者,您也可以使用TPL在任务中执行长时间运行的功能,该任务将管理OS线程池。
var result = Task.Run(() => downloadFromUri(uri)).Result;