我正在使用以下代码成功下载文件。因为我希望它们在Application Startup上下载,所以我不想阻止任何东西 - > async。
但是我面临的问题是,即使URI路径完全无意义,它也会生成一个空文件,而不是像msdn中所述那样引发错误
谁能帮我?
private void DownloadDocuments()
{
using (WebClient myWebClient = new WebClient())
{
try
{
Log("load1");
myWebClient.DownloadFileAsync(new Uri(documentsUri + documentActivation), documentspath + "\\" + documentActivation);
}
catch (WebException)
{
Log("Guide Activation Download failed.");
}
catch (InvalidOperationException)
{
Log("Guide Activation could not be saved.");
}
}
using (WebClient myWebClient = new WebClient())
{
try
{
Log("load2");
myWebClient.DownloadFileAsync(new Uri(documentsUri + documentFloating), documentspath + "\\" + documentFloating);
}
catch (WebException)
{
Log("Guide Floating Download failed.");
}
catch (InvalidOperationException)
{
Log("Guide Floating could not be saved.");
}
}
using (WebClient myWebClient = new WebClient())
{
try
{
Log("load3");
myWebClient.DownloadFileAsync(new Uri(documentsUri + documentSeat), documentspath + "\\" + documentSeat);
}
catch (WebException)
{
Log("Guide Seat Download failed.");
}
catch (InvalidOperationException)
{
Log("Guide Seat could not be saved.");
}
}
}
WebClient.DownloadFileAsync不会在HTTP请求失败时抛出异常。您需要订阅DownloadFileCompleted事件以获得错误通知。
但是,一旦我们在C#中具有基于任务的异步/等待功能,我不建议搞乱事件处理程序回调:WebClient.DownloadFileTaskAsync使用起来更方便。
考虑到有关并行处理的注释,您可以执行以下操作:
static async Task DownloadDocumentAsync(Uri uri, string fileName)
{
using (var webClient = new WebClient())
{
try
{
await webClient.DownloadFileTaskAsync(uri, fileName);
}
catch (WebException ex)
{
Log($"Downloading {uri} failed. {ex.Message}");
throw;
}
catch (InvalidOperationException)
{
Log($"Saving {uri} to {fileName} failed. File is in use.");
throw;
}
}
}
然后你的应用程序启动逻辑:
var baseUri = new Uri(documentsUri);
var downloadTasks = new[]
{
DownloadDocumentAsync(new Uri(baseUri, documentActivation), Path.Combine(documentspath, documentActivation)),
DownloadDocumentAsync(new Uri(baseUri, documentFloating), Path.Combine(documentspath, documentFloating)),
DownloadDocumentAsync(new Uri(baseUri, documentSeat), Path.Combine(documentspath, documentSeat)),
};
try
{
Task.WaitAll(downloadTasks);
}
catch (AggregateException)
{
// handle the case when some of the download tasks failed
}
这样下载任务就会并行执行,但Task.WaitAll会阻塞,直到完成所有任务。如果你想保持异步,你需要await Task.WhenAll
。