Asynch a synchronous method with await async

Posted on 5/17/2014 @ 9:27 AM in #Vanilla .NET by | Feedback | 1291 views

Stock this in “bag of tricks”, but very frequently we run into APIs that do not offer Asynch methods.
But between C# ‘s amazing set of features, and asynch await keywords, there is a lot you can do.

For instance, consider this code -

   1:  ShowMessage("Saving ..");
   2:  entities.SaveChanges();
   3:  ShowMessage("Saved ...");

The problem with this code is, the .SaveChanges() method is synchronous. Its going to block our UI.

As Miguel de Icaza says, lets not be animals and use Asynch. Here is how -

   1:  ShowMessage("Saving ..");
   2:  await Task.Run(() => { 
   3:      entities.SaveChanges(); 
   4:  }).ContinueWith((o) => {
   5:      ShowMessage("Saved ...");
   6:  });


Sound off but keep it civil:

Older comments..