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

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

问题描述

我有以下的code:

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下载。这两个时间异步课程。然而,code不能编译,因为,

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

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

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

编辑:

好消息是, C#6.0将有可能让等待无论是在渔获物和通话finally块的。

推荐答案

更新: C#6.0支持渔获等待

旧的答案:您可以重写code键移动等待块是用一个标志:

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天全站免登陆