Entity Framework SaveChanges() vs. SaveChangesAsync() and Find() vs. FindAsync()

async-await c# entity-framework

Accepted Answer

Your program creates the request, sends it, and then waits for a response whenever you need to perform an operation on a remote server. I will applySaveChanges() and SaveChangesAsync() as an illustration, but the same is true forFind() and FindAsync() .

Think of a list you have.myList You need to add more than 100 items to your database. Your function would resemble the following to insert that:

using(var context = new MyEDM())
{
    context.MyTable.AddRange(myList);
    context.SaveChanges();
}

Create an instance of firstMyEDM enlarge the listmyList to the deskMyTable then dialSaveChanges() to maintain the database updates. The records are committed, and everything goes according to plan, but your software is unable to do anything else until the commit is complete. Depending on what you are committing, this could take a while. I have had a save take two minutes to update when you were committing changes to the records; this is required!

You have two options for resolving this issue. The first is that you can create a new thread specifically for the insert. While this will allow the caller thread to resume its operations, you have now established a new thread that will do nothing except wait. That overhead is unnecessary, and this is what theasync await solves patterns.

For I/O opperations,await becomes your best pal in no time. We can change the code portion from above to be:

using(var context = new MyEDM())
{
    Console.WriteLine("Save Starting");
    context.MyTable.AddRange(myList);
    await context.SaveChangesAsync();
    Console.WriteLine("Save Complete");
}

Although it is a relatively minor adjustment, it has a significant impact on the effectiveness and performance of your code. So what occurs? The code starts out the same way: You create an instance ofMyEDM including yourmyList to MyTable . however, if you callawait context.SaveChangesAsync() when code brings us back to the calling function! is run. Your code can therefore continue to run while you wait for all of those records to commit. Let's say the signature of the function that included the aforementioned code waspublic async Task SaveRecords(List<MyTable> saveList) the calling function might resemble the following:

public async Task MyCallingFunction()
{
    Console.WriteLine("Function Starting");
    Task saveTask = SaveRecords(GenerateNewRecords());

    for(int i = 0; i < 1000; i++){
        Console.WriteLine("Continuing to execute!");
    }

    await saveTask;
    Console.Log("Function Complete");
}

I'm not sure why you would have a function like this, but what it produces demonstrates howasync await works. Let's first discuss what occurs.

Execution begins.MyCallingFunction , Function Starting then Save Starting is performed once the data is written to the console.SaveChangesAsync() is contacted. At this moment, the process switches back toMyCallingFunction and enters the for loop up to 1000 times, writing "Continuing to Execute." WhenSaveChangesAsync() executes, control is returned to theSaveRecords perform, writeSave Complete to the game console. once all is doneSaveRecords upon completion, execution will proceed inMyCallingFunction Right there, at that timeSaveChangesAsync() completed. Confused? Here is an illustration of output:

Function Starting
Save Starting
Continuing to execute!
Continuing to execute!
Continuing to execute!
Continuing to execute!
Continuing to execute!
....
Continuing to execute!
Save Complete!
Continuing to execute!
Continuing to execute!
Continuing to execute!
....
Continuing to execute!
Function Complete!

Or perhaps:

Function Starting
Save Starting
Continuing to execute!
Continuing to execute!
Save Complete!
Continuing to execute!
Continuing to execute!
Continuing to execute!
....
Continuing to execute!
Function Complete!

That is its allure.async await Whilst you wait for things to finish, your code can keep running. As your calling function, you would actually have something more akin to this:

public async Task MyCallingFunction()
{
    List<Task> myTasks = new List<Task>();
    myTasks.Add(SaveRecords(GenerateNewRecords()));
    myTasks.Add(SaveRecords2(GenerateNewRecords2()));
    myTasks.Add(SaveRecords3(GenerateNewRecords3()));
    myTasks.Add(SaveRecords4(GenerateNewRecords4()));

    await Task.WhenAll(myTasks.ToArray());
}

There are four separate record-saving functions running here from in the same manner.MyCallingFunction will be much quicker utilizingasync await than if the personSaveRecords functions were repeatedly called.

The one subject I have not yet addressed is theawait keyword. This halts the execution of the current function until whateverTask You're waiting for results. hence in the originalMyCallingFunction the phraseFunction Complete is written to the console after theSaveRecords function is completed.

To cut to the chase, if you have the choice to useasync await , you really ought to do it because it will make your application run much faster.

157
10/10/2018 10:18:01 PM

Popular Answer

This assertion is untrue:

On server side, when we use Async methods, we also need to add await.

There is no need to include "await,"await is basically a useful keyword in C# that allows you to add other lines of code after the call; but, these additional lines of code won't be executed until the Save process has finished. However, as you noted, you might achieve that by simply callingSaveChanges in place ofSaveChangesAsync .

However, an async call is fundamentally much more than that. The concept behind this is that if you can complete other tasks (on the server) while the Save process is running, you should do so.SaveChangesAsync . "Await" must not be used. make a callSaveChangesAsync and then carry on with other tasks in tandem. This may involve, in a web application, sending a response to the client even before the Save process is finished. Naturally, you should check the final Save result so that, if it fails, you may inform your user or record it in some other way.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow