Page 127 - CSharp/C#
P. 127

As of C# 6.0, the await keyword can now be used within a catch and finally block.


         try {
            var client = new AsyncClient();
            await client.DoSomething();
         } catch (MyException ex) {
            await client.LogExceptionAsync();
            throw;
         } finally {
            await client.CloseAsync();
         }


        5.06.0


        Prior to C# 6.0, you would need to do something along the lines of the following. Note that 6.0 also
        cleaned up the null checks with the Null Propagating operator.


         AsynClient client;
         MyException caughtException;
         try {
              client = new AsyncClient();
              await client.DoSomething();
         } catch (MyException ex) {
              caughtException = ex;
         }

         if (client != null) {
             if (caughtException != null) {
                await client.LogExceptionAsync();
             }
             await client.CloseAsync();
             if (caughtException != null) throw caughtException;
         }


        Please note that if you await a task not created by async (e.g. a task created by Task.Run), some
        debuggers may break on exceptions thrown by the task even when it is seemingly handled by the
        surrounding try/catch. This happens because the debugger considers it to be unhandled with
        respect to user code. In Visual Studio, there is an option called "Just My Code", which can be
        disabled to prevent the debugger from breaking in such situations.


        Web.config setup to target 4.5 for correct async behaviour.


        The web.config system.web.httpRuntime must target 4.5 to ensure the thread will renter the
        request context before resuming your async method.


         <httpRuntime targetFramework="4.5" />


        Async and await have undefined behavior on ASP.NET prior to 4.5. Async / await will resume on
        an arbitrary thread that may not have the request context. Applications under load will randomly
        fail with null reference exceptions accessing the HttpContext after the await. Using
        HttpContext.Current in WebApi is dangerous because of async






        https://riptutorial.com/                                                                               73
   122   123   124   125   126   127   128   129   130   131   132