我有以下代码:
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 下载。当然,两者都是异步的。但是代码无法编译,因为
error CS1985: Cannot await in the body of a catch clause
好吧,无论出于何种原因,它都是被禁止的,但是这里正确的代码模式是什么?
编辑:
好消息是C# 6.0 will likely allow await calls both in catch and finally blocks .
最佳答案
更新: C# 6.0 supports await in catch
旧答案:您可以重写该代码以使用标志从 catch
block 中移动 await
:
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" ) );
关于c# - 在捕获 block 中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868123/