Entity Framework - Asynchronous Query



Asynchronous programming involves executing operations in the background so that the main thread can continue its own operations. This way the main thread can keep the user interface responsive while the background thread is processing the task at hand.

  • Entity Framework 6.0 supports asynchronous operations for querying and saving of data.

  • Asynchronous operations can help your application in the following ways −

    • Make your application more responsive to user interactions
    • Improve the overall performance of your application
  • You can execute asynchronous operations in various ways. But async/await keywords were introduced in .NET Framework 4.5 which makes your job simple.

  • The only thing you need to follow is the async/await pattern as illustrated by the following code fragment.

Let’s take a look at the following example (without using async/await) in which DatabaseOperations method saves a new student to the database and then retrieves all students from the database and at the end some additional message is printed on the console.

class Program {

   static void Main(string[] args) {
      Console.WriteLine("Database Operations Started");
      DatabaseOperations();
		
      Console.WriteLine();
      Console.WriteLine("Database Operations Completed");
      Console.WriteLine();
      Console.WriteLine("Entity Framework Tutorials");
		
      Console.ReadKey();
   }

   public static void DatabaseOperations() {

      using (var context = new UniContextEntities()) {

         // Create a new student and save it

         context.Students.Add(new Student {
            FirstMidName = "Akram", 
            LastName = "Khan", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())});

         Console.WriteLine("Calling SaveChanges.");
         context.SaveChanges();
         Console.WriteLine("SaveChanges completed.");

         // Query for all Students ordered by first name

         var students = (from s in context.Students
            orderby s.FirstMidName select s).ToList();

         // Write all students out to Console

         Console.WriteLine();
         Console.WriteLine("All Student:");

         foreach (var student in students) {
            string name = student.FirstMidName + " " + student.LastName;
            Console.WriteLine(" " + name);
         }
      }
   }
}

When the above code is executed, you will receive the following output −

Calling SaveChanges.
SaveChanges completed.
All Student:
Akram Khan
Ali Khan
Ali Alexander
Arturo Anand
Bill Gates
Gytis Barzdukas
Laura  Nornan
Meredith fllonso
Nino Olioetto
Peggy Justice
Yan Li

Entity Framework Tutorials

Let’s use the new async and await keywords and make the following changes to Program.cs

  • Add System.Data.Entity namespace which will give EF async extension methods.

  • Add System.Threading.Tasks namespace which will allow us to use the Task type.

  • Update DatabaseOperations to be marked as async and return a Task.

  • Call the Async version of SaveChanges and await its completion.

  • Call the Async version of ToList and await the result.

class Program {

   static void Main(string[] args) {
      var task = DatabaseOperations();
      Console.WriteLine();
      Console.WriteLine("Entity Framework Tutorials");
      task.Wait();
      Console.ReadKey();
   }

   public static async Task DatabaseOperations() {

      using (var context = new UniContextEntities()) {

         // Create a new blog and save it

         context.Students.Add(new Student {
            FirstMidName = "Salman", 
            LastName = "Khan", 
            EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())});

         Console.WriteLine("Calling SaveChanges.");
         await context.SaveChangesAsync();
         Console.WriteLine("SaveChanges completed.");

         // Query for all Students ordered by first name

         var students = await (from s in context.Students 
            orderby s.FirstMidName select s).ToListAsync();

         // Write all students out to Console

         Console.WriteLine();
         Console.WriteLine("All Student:");

         foreach (var student in students) {
            string name = student.FirstMidName + " " + student.LastName; 
            Console.WriteLine(" " + name);
         }
      }
   }
}

On execution, it will produce the following output.

Calling SaveChanges.
Entity Framework Tutorials
SaveChanges completed.
All Student:
Akram Khan
Ali Khan
Ali Alexander
Arturo Anand
Bill Gates
Gytis Barzdukas
Laura  Nornan
Meredith fllonso
Nino Olioetto
Peggy Justice
Salman Khan
Yan Li

Now that the code is asynchronous, you can observe a different execution flow of your program.

  • SaveChanges begins to push the new Student to the database and then the DatabaseOperations method returns (even though it hasn't finished executing) and program flow in the Main method continues.

  • Message is then written to the console.

  • The managed thread is blocked on the Wait call until the database operation completes. Once it completes, the remainder of our DatabaseOperations will be executed.

  • SaveChanges completes.

  • Retrieved all the student from the database and is written to the Console.

We recommend that you execute the above example in a step-by-step manner for better understanding.

Advertisements