gpt4 book ai didi

c# - 在 "await DownloadTaskAsync"上调用 WebClient.CancelAsync 时出现 WebException

转载 作者:太空宇宙 更新时间:2023-11-03 17:37:37 26 4
gpt4 key购买 nike

这很好用:

private WebClient _webClient;

private void ButtonStart_Click(object sender, RoutedEventArgs e) {
using (_webClient = new WebClient()) {
_webClient.DownloadFileTaskAsync("https://speed.hetzner.de/100MB.bin", @"D:\100MB.bin");
}
}

private void ButtonStop_Click(object sender, RoutedEventArgs e) {
_webClient.CancelAsync();
}

虽然这段代码(注意异步/等待模式)...:

private WebClient _webClient;

private async void ButtonStart_Click(object sender, RoutedEventArgs e) {
using (_webClient = new WebClient()) {
await _webClient.DownloadFileTaskAsync("https://speed.hetzner.de/100MB.bin", @"D:\100MB.bin");
}
}

private void ButtonStop_Click(object sender, RoutedEventArgs e) {
_webClient.CancelAsync();
}

...抛出以下异常:

System.Net.WebException

The request was aborted: The request was canceled.

   at System.Net.ConnectStream.EndRead(IAsyncResult asyncResult)
at System.Net.WebClient.DownloadBitsReadCallbackState(DownloadBitsState state, IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at WpfApp1.MainWindow.<ButtonStart_Click>d__2.MoveNext() in WpfApp1\MainWindow.xaml.cs:line 19

如何在不引发异常的情况下取消以 await WebClient.DownloadFileTaskAsync() 开始的任务?

最佳答案

异常(exception)正是它应该的工作方式。

如果您不希望该异常从您的事件处理程序传播出去,则捕获该异常。

关于c# - 在 "await DownloadTaskAsync"上调用 WebClient.CancelAsync 时出现 WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com