I am working with Entity Framework with ASP MVC and I have the following question, should I always use async methods? Or on what should I base myself to choose between one and the other?
asynchronous
private static async Task AddStudent()
{
Student myStudent = new Student();
using (var context = new SchoolDBEntities())
{
context.Students.Add(myStudent);
await context.SaveChangesAsync();
}
}
synchronous
private static void AddStudent()
{
Student myStudent = new Student();
using (var context = new SchoolDBEntities())
{
context.Students.Add(myStudent);
context.SaveChanges();
}
}
You should use async/await when you have a task that takes considerable time and you need to wait for it to finish. They are usually processes that involve Input/Output operations and the compiler generates a finite state machine when invoking them. If your program doesn't need to wait for the result of a complex operation, then you can use a traditional synchronous approach since it will execute independently.
In your example, if when saving the student information you want to show those changes immediately, you must use the asynchronous approach, otherwise you will not know if the student object has been saved to disk or not since it is difficult to know if the write operation was successful. will execute immediately, getting information not updated on the next data load. If instead you don't mind displaying/using the data immediately after calling the save method you can definitely use the synchronous method. This causes a separate process to be launched for each non-immediate task, without blocking execution in the block of code.
To make it better understood we write the following example:
Now we explain:
Task longTask = SaveChangesAsync() is executed independently in a separate thread. Code executed after this line continues to execute normally on the main thread and can take as long as it needs. Then in the line int result = await longTask; The main thread waits for the thread created with SaveChangesAsync to continue execution normally. In the event that the independent code of the main task takes more than 1 second, the SaveChangesAsync method will return 1 directly since the code has been executed in an independent thread keeping the state.