在“await DownloadTaskAsync”上调用WebClient.CancelAsync时出现WebException

问题描述 投票:1回答:2

这很好用:

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();
}

虽然这段代码(注意async / await模式)......:

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

请求已中止:请求已取消。

   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()启动的任务?

c# async-await webclient
2个回答
7
投票

唯一的例外是它应该如何工作。

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


3
投票

您可以像这样捕获异常:

using (_webClient = new WebClient())
{
    try
    {
        await _webClient.DownloadFileTaskAsync("https://speed.hetzner.de/100MB.bin", @"D:\100MB.bin");
    }
    catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
    {
        Console.WriteLine("Cancelled");
    }
}

更新:如何更改CancelAsync的默认行为,以避免必须捕获异常:

public static Task<bool> OnCancelReturnTrue(this Task task)
{
    return task.ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            if (t.Exception.InnerException is WebException webEx
                && webEx.Status == WebExceptionStatus.RequestCanceled) return true;
            throw t.Exception;
        }
        return t.IsCanceled;
    }, TaskContinuationOptions.ExecuteSynchronously);
}

用法示例:

bool cancelled = await _webClient.DownloadFileTaskAsync(
    "https://speed.hetzner.de/100MB.bin", @"D:\100MB.bin").OnCancelReturnTrue();
if (cancelled) Console.WriteLine("Cancelled");
© www.soinside.com 2019 - 2024. All rights reserved.