在 catch 块中等待 [英] Await in catch block

查看:35
本文介绍了在 catch 块中等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

WebClient wc = new WebClient();
string result;
try
{
  result = await wc.DownloadStringTaskAsync( new Uri( "http://badurl" ) );
}
catch
{
  result = await wc.DownloadStringTaskAsync( new Uri( "http://fallbackurl" ) );
}

基本上我想从一个 URL 下载,当它因异常而失败时,我想从另一个 URL 下载.当然,这两个时间都是异步的.但是代码不能编译,因为

Basically I want to download from a URL and when it fails with an exception I want to download from another URL. Both time async of course. However the code does not compile, because of

错误 CS1985:无法在 catch 子句的主体中等待

error CS1985: Cannot await in the body of a catch clause

好的,无论出于何种原因都被禁止,但这里的正确代码模式是什么?

OK, it's forbidden for whatever reason but what's the correct code pattern here?

好消息是 C# 6.0 可能允许在 catch 和finally 块.

推荐答案

更新: C# 6.0 支持在 catch 中等待

旧答案:您可以重写该代码以使用标志将 awaitcatch 块中移出:

Old Answer: You can rewrite that code to move the await from the catch block using a flag:

WebClient wc = new WebClient();
string result = null;
bool downloadSucceeded;
try
{
  result = await wc.DownloadStringTaskAsync( new Uri( "http://badurl" ) );
  downloadSucceeded = true;
}
catch
{
  downloadSucceeded = false;
}

if (!downloadSucceeded)
  result = await wc.DownloadStringTaskAsync( new Uri( "http://fallbackurl" ) );

这篇关于在 catch 块中等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆