6

Can explain somebody what is the main differences between SaveChanges and SaveChangesAsync ? Where I should use SaveChangesAsync and when ? How's the performance varies ?

I have two examples here :

Asyncronous function:

private static async void AddStudent()
{
   Student myStudent = new Student();
   using (var context = new SchoolDBEntities())
   {           
      context.Students.Add(myStudent);
      await context.SaveChangesAsync();           
   }
}

Syncronous function:

private static void AddStudent()
{
   Student myStudent = new Student();
   using (var context = new SchoolDBEntities())
   {           
      context.Students.Add(myStudent);
      context.SaveChanges();           
   }
}

Thanks in advance !.

1 Answer 1

10

Your async example should be like this:

private static async Task AddStudent()
{
   Student myStudent = new Student();
   using (var context = new SchoolDBEntities())
   {           
      context.Students.Add(myStudent);
      await context.SaveChangesAsync();           
   }
}

The difference between a synchronous and asynchronous calls is that the latter does not block a calling thread. Database operations are I/O bound: network isn't blazing fast and SQL queries take time to process. So, instead of waiting for the result (blocking a thread) we can return that thread back to thread pool so that concurrent user requests can be processed. This is essential for scaling when your site is hit by multiple users simultaneously. But, in order to utilize the async/await feature your whole call chain must be async up the stack.

I'd suggest to read some basic intros on async/await like this.

Sign up to request clarification or add additional context in comments.

4 Comments

I/O bound operations perform a lot of I/O calls like file, socket, netpipe read and writes. Those operations are considered slow and don't require almost any CPU power (they are naturally event based). The contrary is CPU bound operations, i.e. ones that do a lot of computations like a image processing, in-memory collection aggregations, etc.
Thanks again, @UserControl
I have 100% cpu load during savechanges. How would async/await help if it has to do a lot of cpu bound in memory dirty checking?
I'd like just to add that you should always await for SaveChangesAsync since EF does not support multiple saves at the same time. learn.microsoft.com/en-us/ef/core/saving/async Also, there's actually a great advantage on using these async methods. For example, you can keep receiving other requests in your webApi when saving data or doing lots of sutuff, or improve user experience not freezing the interface when you're in a desktop application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.