Await in catch block

前端 未结 9 1506
醉梦人生
醉梦人生 2020-11-28 11:14

I have the following code:

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


        
9条回答
  •  孤街浪徒
    2020-11-28 11:44

    Update: C# 6.0 supports await in catch


    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" ) );
    

提交回复
热议问题