Await in catch block

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

    You can use a lambda expression as follows:

      try
        {
            //.....
        }
        catch (Exception ex)
        {
            Action<Exception> lambda;
    
            lambda = async (x) =>
            {
                // await (...);
            };
    
            lambda(ex);
        }
    
    0 讨论(0)
  • 2020-11-28 11:26

    In a similar instance, I was unable to await in a catch block. However, I was able to set a flag, and use the flag in an if statement (Code below)

    ---------------------------------------...

    boolean exceptionFlag = false; 
    
    try 
    { 
    do your thing 
    } 
    catch 
    { 
    exceptionFlag = true; 
    } 
    
    if(exceptionFlag == true){ 
    do what you wanted to do in the catch block 
    }
    
    0 讨论(0)
  • 2020-11-28 11:32

    This seems to work.

            WebClient wc = new WebClient();
            string result;
            Task<string> downloadTask = wc.DownloadStringTaskAsync(new Uri("http://badurl"));
            downloadTask = downloadTask.ContinueWith(
                t => {
                    return wc.DownloadStringTaskAsync(new Uri("http://google.com/")).Result;
                }, TaskContinuationOptions.OnlyOnFaulted);
            result = await downloadTask;
    
    0 讨论(0)
  • 2020-11-28 11:37

    Awaiting in a catch block is now possible as of the End User Preview of Roslyn as shown here (Listed under Await in catch/finally) and will be included in C# 6.

    The example listed is

    try … catch { await … } finally { await … }
    

    Update: Added newer link, and that it will be in C# 6

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

    Give this a try:

             try
            {
                await AsyncFunction(...);
            }
    
            catch(Exception ex)
            { 
                Utilities.LogExceptionToFile(ex).Wait();
                //instead of "await Utilities.LogExceptionToFile(ex);"
            }
    

    (See the Wait() ending)

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

    Use C# 6.0. see this Link

    public async Task SubmitDataToServer()
    {
      try
      {
        // Submit Data
      }
      catch
      {
        await LogExceptionAsync();
      }
      finally
      {
        await CloseConnectionAsync();
      }
    }
    
    0 讨论(0)
提交回复
热议问题