2 回答
TA贡献1934条经验 获得超2个赞
您可以像这样捕获异常:
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");
- 2 回答
- 0 关注
- 147 浏览
添加回答
举报