Reputation: 48327
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 !.
Upvotes: 6
Views: 12574
Reputation: 15149
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.
Upvotes: 10