Page 131 - CSharp/C#
P. 131

asynchronous operation. The Task returned by GetByKeyAsync is passed directly to the calling
        method, where it will be awaited.


        Important: Returning the Task instead of awaiting it, changes the exception behavior of the
        method, as it won't throw the exception inside the method which starts the task but in the method
        which awaits it.


         public Task SaveAsync()
         {
             try {
                 return dataStore.SaveChangesAsync();
             }
             catch(Exception ex)
             {
                 // this will never be called
                 logger.LogException(ex);
             }
         }

         // Some other code calling SaveAsync()

         // If exception happens, it will be thrown here, not inside SaveAsync()
         await SaveAsync();


        This will improve performance as it will save the compiler the generation of an extra async state
        machine.


        Blocking on async code can cause deadlocks


        It is a bad practice to block on async calls as it can cause deadlocks in environments that have a
        synchronization context. The best practice is to use async/await "all the way down." For example,
        the following Windows Forms code causes a deadlock:


         private async Task<bool> TryThis()
         {
             Trace.TraceInformation("Starting TryThis");
             await Task.Run(() =>
             {
                 Trace.TraceInformation("In TryThis task");
                 for (int i = 0; i < 100; i++)
                 {
                     // This runs successfully - the loop runs to completion
                     Trace.TraceInformation("For loop " + i);
                     System.Threading.Thread.Sleep(10);
                 }
             });

             // This never happens due to the deadlock
             Trace.TraceInformation("About to return");
             return true;
         }

         // Button click event handler
         private void button1_Click(object sender, EventArgs e)
         {
             // .Result causes this to block on the asynchronous call



        https://riptutorial.com/                                                                               77
   126   127   128   129   130   131   132   133   134   135   136