Await in catch block

前端 未结 9 1437
醉梦人生
醉梦人生 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:41

    You could put the await after the catch block followed by a label, and put a goto in the try block. (No, really! Goto's aren't that bad!)

    0 讨论(0)
  • 2020-11-28 11:43

    The pattern I use to rethrow the exception after await on a fallback task:

    ExceptionDispatchInfo capturedException = null;
    try
    {
      await SomeWork();
    }
    catch (Exception e)
    {
      capturedException = ExceptionDispatchInfo.Capture(e);
    }
    
    if (capturedException != null)
    {
      await FallbackWork();
      capturedException.Throw();
    }
    
    0 讨论(0)
  • 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" ) );
    
    0 讨论(0)
提交回复
热议问题